我寫過一個包含用戶交互的表單的程序。因爲有很多事件綁定到不同的按鈕,我寫了一個循環來分析一些包含表單輸入信息的JS。下面是一些示例數據:用jQuery替換jQuery.bind
var value = 0,
forms = {
place_controls : {
attrs : {
'class' : 'place-form'
},
input : {
place_x : {
attrs : {
type : 'text',
},
events : {
change : function() {
value = 10;
}
}
},
place_y : {
attrs : {
type : 'text',
},
events : {
change : function() {
value = 50
}
}
}
}
}
}
數據被此解析:
$.each(forms, function (form_index, form) {
var $form_markup = $('<form>').attr(form.attrs);
// Next: loop through each input element of the form we've reached
$.each(form.input, function (element_index, element) {
var $elem = $('<input>').attr(element.attrs);
$elem.appendTo($form_markup);
if (element.events !== undefined) {
$.each(element.events, function (event_index, event) {
$elem.bind(event_index, event);
//$form_markup.on(event_index, $elem, event);
});
}
});
$form_markup.appendTo($form_goes_here);
});
正如你所看到的,我使用.bind()
的那一刻,但我想用.on()
。不幸的是,當我這樣做時,表單中的所有項都綁定到函數解析的最後一個事件。當我使用.bind()
一切都將按計劃 - 即點擊「place_x」設定值爲10,點擊「place_y」設置值50
當使用.on()
,無論我設置的值更改爲50,這我假設是因爲最後一個函數正在與每個事件綁定。
任何人都可以看到我做錯了什麼嗎?
更新:有很多不同的方法來做到這一點,我後來改變了我的代碼的工作方式,但是這個問題與爲什麼.bind()
正在工作以及爲什麼.on()
不是。
爲什麼ypu想改變它? –
您應該閱讀['.prop()'](http://api.jquery.com/prop/),因爲這可能是您想要使用的而不是'.attr()'。 – Pointy
只是因爲on()應該是更高效的,但不管我爲什麼它不起作用而困惑,現在我真的想修復它! – Alex