[英]How to detect clicks on generated elements?
我正在從JSON數據中創建一組元素:示例:
{
'name':'form',
'elements':[
{'name':'bt1','type':'button','value':'hello','order':'1'},
{'name':'img1','type':'image','value':'http://www.images.com/img.jpg','order':'2'}]
}
我用這個json做的是創建一個帶有'elements'中描述的元素的表單,代碼如下:
(我用mumbo jumbo + jquery代碼得到了這個草稿)
$('#container').html();//clears the container
for each element in elements do
switch element.type
case 'button':
$('#container').append('<input type="submit" value="'+element.value + ... etc');
end case
case 'image':
insert image bla bla bla
end switch
end for each
我想檢測一個元素是否被點擊或其他類型的操作,如鼠標懸停等。如何將其綁定到元素? 另外,如何在不破壞元素的情況下更新元素?
編輯 :我暗示一些重要的東西,我的壞:我需要將元素javascript對象中的數據與生成的html元素鏈接起來。 觸發操作時檢索的數據字段。 這就是所有這一切的特征。
你有兩個選擇。 您可以在創建元素后綁定偵聽器,如下所示:
var $input = $('<input type="submit" value="'+element.value + ... etc')
.focus(...).blur(...).etc.;
$('#container').append($input);
或者,您可以使用事件委派。 在初始頁面加載時,您可以執行以下操作:
$("#container").on( "focus", "input", function(){...});
這將涵蓋#container
中當前或稍后動態添加的所有輸入元素。 您可以在on docs上閱讀有關事件委派的更多信息。
要檢測動態添加元素上的事件,您應該使用on()
表示jQuery 1.7+和.live()
用於以前的版本。
編輯:是的,正如詹姆斯在評論中指出的那樣, delegate()
始終被推薦為live()
。
構建表單非常簡單,因為您基本上映射了對象sytanx中元素的所有屬性。 因此,我們可以創建這些元素,只需選擇一個標記,並將屬性對象作為jQuery函數的第二個參數傳遞:
/* Container reference, counting variable */
var container = $("#container"), i = 0;
/* Clear out the container */
container.html("");
/* Cycle through each element */
while ( current = data.elements[i++] ) {
/* Evaluate the value of the current type */
switch ( current.type ) {
/* Since <input type='button|image'> are so similar, we fall-through */
case "button":
case "image" :
/* Choose a base element, pass in object of properties, and append */
$("<input>", current).appendTo(container);
break;
}
}
在注冊點擊或任何其他類型的事件時,我們將使用$.on
方法。 因為我們傳入一個選擇器(在這種情況下是“輸入”),所以這不僅會匹配所有現有元素,還會匹配所有未來元素。
/* Listen for all clicks on input elements within the container */
container.on("click", "input", function(){
/* We have a button, and an image. Alert either the value or src */
alert( this.value || this.src );
});
如果您的js代碼很短,只需在追加函數中添加您的js代碼即可。 append('<input type="submit" onclick="xxxx" value="'+element.value + ... etc');
如果你的js代碼很長,你可以為你的新元素添加一個id。 並向id添加事件。
$("#idxx").click(function(){alert("Hello");});
要么直接綁定元素
$input = $('<input type="submit" value="'+element.value + ... etc');
$input.on('click', function() {
// do something
}
$('#container').append($input);
或者將綁定放在父級上,以檢查內部點擊的選擇。
$('#container').on('click', 'input', function() {
// do something
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.