您有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