开发者

jQuery Click event on object added with JavaScript not working

开发者 https://www.devze.com 2022-12-27 10:44 出处:网络
I\'m working on a quiz for school but I\'ve bumped into a problem. I got a JavaScript library for custom radio buttons (CUSTOM FORM ELEMENTS by Ryan Fait if it\'s helping). The script hides the input

I'm working on a quiz for school but I've bumped into a problem. I got a JavaScript library for custom radio buttons (CUSTOM FORM ELEMENTS by Ryan Fait if it's helping). The script hides the input buttons and adds custom styled spans instead.

Desired behaviour, when I click one a span (added with JavaScript) I want to remove disabled attribute from my "Next Question"-button which when pressed takes you to the next question. I don't want users to accidentally proceed to the next question, without choosing an answer. The problem is when I press the added spans nothing happens, but when I press another identical span which I have ad开发者_如何学运维ded in the HTML it works just as intended.

The span got the class radio, which I'm doing a lookup on with jQuery.

Short: Can't get jQuery .click() functions to work with spans added using JavaScript earlier in the document.


You are looking for jQuery's live() function. You would do something like:

$(".radio").live("click", function() {
    // Enable the button here
});

Your other option would be to use the new delegate() function if you have jQuery 1.4.2 included on your page. Similar syntax, however, it only scans within the element it's called on for child elements of the kind you want to bind an eventListener to and I believe it has much less of a performance impact on large pages. (Not applicable in your case, but it's always good to practice with the best tools.)

$("element_containing_radio_buttons").delegate(".radio" "click", function() {
   // Enable the button here
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号