简体   繁体   English

使用 JavaScript 添加的对象上的 jQuery Click 事件不起作用

[英]jQuery Click event on object added with JavaScript not working

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).我有一个用于自定义单选按钮的 JavaScript 库(Ryan Fait 的 CUSTOM FORM ELEMENTS,如果有帮助的话)。 The script hides the input buttons and adds custom styled spans instead.该脚本隐藏输入按钮并添加自定义样式的spans

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.所需的行为,当我单击一个span (用 JavaScript 添加)时,我想从我的“下一个问题”按钮中删除disabled属性,按下该按钮时会将您带到下一个问题。 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 added in the HTML it works just as intended.问题是当我按下添加的跨度时没有任何反应,但是当我按下我在 HTML 中添加的另一个相同的跨度时,它会按预期工作。

The span got the class radio, which I'm doing a lookup on with jQuery. span获得了类收音机,我正在使用 jQuery 进行查找。

Short: Can't get jQuery .click() functions to work with spans added using JavaScript earlier in the document.简短:无法使用 jQuery .click()函数来处理文档中先前使用 JavaScript 添加的跨度。

You are looking for jQuery's live() function.您正在寻找 jQuery 的live()函数。 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.如果您的页面中包含 jQuery 1.4.2,您的另一个选择是使用新的delegate()函数。 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.然而,类似的语法,它只在它被调用的元素内扫描你想要将 eventListener 绑定到的那种子元素,我相信它对大页面的性能影响要小得多。 (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
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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