您有jQuery的标签在你的问题,所以我将提供一个jQuery答案:
你会使用jQuery's on()
method到事件委托给你的复选框的非动态的祖先:
$('elem').on('change', 'input[type="checkbox"]', function() {
...
});
哪里elem
是您的复选框的非动态的祖先。
在您的JSFiddle中,您的复选框不是动态的,但假设它是最接近的非动态祖先将是文档的body
。因此,我们可以使用:
$('body').on('change', 'input[type="checkbox"]', function() {
testing('hello', '1');
});
JSFiddle demo。
您可能希望通过传递来扩展这个“你好”和“1”为data-*
attributes:
<input type="checkbox" name="test" data-newvalue="hello" data-spanid="1" />
<input type="checkbox" name="test" data-newvalue="second" data-spanid="2" />
在这里,我创建了两个复选框与我们两家data-*
属性。在我们的jQuery方法,我们可以拉这些值,并使用jQuery's data()
method它们传递到我们testing()
功能:
$('body').on('change', 'input[type="checkbox"]', function() {
testing($(this).data('newvalue'), $(this).data('spanid'));
});
JSFiddle demo。
然后,我们可以修改我们的testing()
功能也使用jQuery:
function testing(newValue, spanID) {
$('#'+spanID).text(newValue);
}
这拉我们spanID(例如“1”)和ID选择$('#1')
内的地方,然后修改使用jQuery的text()
法文本。如果您想修改HTML,jQuery为此还有一个html()
方法。
Final JSFiddle demo。
代码请张贴代码在你的问题。额外的小提琴很好,但你的问题应该没有外部资源。 – Bergi
你的jsfiddle工作,如果函数没有包装在加载函数,行为在jsfiddle,看到没有包装:http://jsfiddle.net/Sz3BK/134/ –
@Bergi我会记住,下一次(可能需要再次帮助嘿嘿) – Rosenthaler