How to add onclick to html element dynamically using javascript

I can create a button element and add an onclick event, as shown below.

elem.onclick=function()
{
alert("qweqweqwe");
}        

How can I use a predefined function instead of defining a function inside an event? Sort of:

elem.onclick=func();
+4
source share
6 answers

add an event element to an element that has a specific function to call:

elem.addEventListener("click", func, false); //where func is your function name
+12
source

The best way that I have learned for myself is as shown below.

const li = document.createElement('li');
        li.innerText = "client";
        li.id ="key";
        li.className = "client-class";
        li.setAttribute("onclick","valid;");
+5
source

1)

function myfunction(){
alert("hello");
}

elem.onclick=myfunction();

2)

var myfunction=function(){
alert("hello");
}
elem.onclick=myfunction;
//or
elem.onclick=myfunction.call();
+3
var clickHandler = function(){

};

elem.onclick = clickHandler;

function clickHandler(){

};

elem.onclick = clickHandler;

functions javascript

, 1, .

, 2, , clickHandler function , .

elem.onclick = function(){};

onclick

. , , , . , w3c . , , .

0

javascript

<div id="test">Click me to alert</div>

-

    document.getElementById("test").onclick=callme;

function callme()
{
    alert("You have clicked me!");
}

0

HTML:

<button>Button</button>
<div id="buttons">
</div>

JS ( jQuery):

$('button').click(function(){
    var dyn_button = '<button onclick="javascript:test()">Dynamic button</button>'
    $('div#buttons').append(dyn_button + "<br>");
});


function test()
{
    alert(123);
}

http://jsfiddle.net/IceManSpy/FaXgr/

-4
source

Source: https://habr.com/ru/post/1533121/


All Articles