我在html中有jquery事件,当我从同一个html按下按钮时会触发这个按钮(按钮的id用于触发jquery)。现在我在同一页面中从javascript(另一个文件)代码动态创建了按钮。当我按下从js创建的按钮(具有相同的ID)时,Jquery没有响应。请帮忙。
代码如下所示。
$(function() {
$( "#dialog" ).dialog({
autoOpen: false,
show: {
effect: "blind",
duration: 1000
},
hide: {
effect: "blind",
duration: 1000
}
});
$( "#opener" ).click(function() {
$( "#dialog" ).dialog( "open" );
});
});
HTML按钮:
<td width="171" ><div>
<input type="button" id="opener" value="SelDimn"> </div></td>
JS按钮:
var cell6 = row.insertCell(5);
var element5 = document.createElement("input");
element5.type = "button";
element5.setAttribute('id', 'opener');
element5.name = 'opener';
element5.value = 'SelDimn';
cell6.appendChild(element5);
答案 0 :(得分:2)
您需要使用event delegation
$(document).on('click', "#opener", function () {
$("#dialog").dialog("open");
});
另请注意,元素的ID必须是唯一的,因此如果有超过1个带有所述ID的按钮,那么这是无效的,因此您需要使用class属性对相似的按钮进行分组
在这种情况下,将其更改为element5.setAttribute('id', 'opener');
至element5.className = 'opener';
然后
$(document).on('click', ".opener", function () {
$("#dialog").dialog("open");
});
dom节点的创建也可以简化为
var cell6 = row.insertCell(5);
$('<input />', {
type = 'button',
'class': 'opener',
name: 'opener',
value: 'SelDimn'
}).appendTo(cell6)