简体   繁体   中英

Unable to attach click event to a dynamically created button

I have created a javascript function to dynamically create a button

function btn(d) {
    var btn = document.createElement("BUTTON");
    var t = document.createTextNode(d);
    btn.appendChild(t);
    btn.className = "myButton";
    btn.onclick = alert('hello');
    document.body.appendChild(btn);
}

when this function is called, alert is poping up even if button is not clicked. I want the alert when button is clicked. May be i am missing something. Please help. Thanks

you are calling the alert function not assigning a function

alert('hello'); // evals immediately.

btn.onclick = function () {
    alert("Hello World"); // gives the button a click handler 
                          // which can be called when clicked
};

Try doing it with jQuery, like so (per your jQuery tag on the question):

function btn(d) {
    var btn = $('<button/>').addClass('myButton').text(d).appendTo('body').click(function (e) {
        alert('hello');
    })
}

onclick应该看起来像:

btn.onclick = function(){alert('hi');};

You are assigning the return value of alert('hello'); to the onclick , while it is expecting a function. The correct way without jQuery would be

if (btn.addEventListener)
  btn.addEventListener ('click',function(){ alert('hello');}, false);
else if (btn.attachEvent)
  btn.attachEvent ('onclick',function(){ alert('hello');});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM