[英]Unable to attach event listeners to dynamically created elements in IE8
概述:
当我单击一个按钮时,我想
问题:
事件处理程序未在IE8中触发正确的元素。 例如,如果我关注表中的最后一个输入,则第一个输入将突出显示。
澄清:
码:
HTML:
<table width="200" border="1" id="myTable">
<tr>
<td>
<input type='text' id='row0col0' name='row0col0'>
</td>
</tr>
</table>
<button id="addRow">Add Row</button>
JS:
function addFocusListener() {
$("input").unbind();
$("input").each(function () {
var $this = $(this);
$this.focus(function () {
var newThis = $(this);
newThis.css('background-color', 'red');
});
});
}
function addRowWithIncrementedIDs() {
var table = document.getElementById("myTable");
var newRow = table.insertRow(-1);
var row = table.rows[0];
var rowNum = newRow.rowIndex;
for (var d = 0; d < row.cells.length; d++) {
var oldCell = row.cells[d];
newCell = oldCell.cloneNode(true);
newRow.appendChild(newCell);
for (var c = 0; c < newCell.childNodes.length; c++) {
var currElement = newCell.childNodes[c];
var id = "row" + rowNum + "col" + d;
$(currElement).attr('name', id);
$(currElement).attr('id', id);
}
}
}
$(document).ready(function () {
$("#addRow").click(function () {
addRowWithIncrementedIDs();
addFocusListener();
});
});
其他可行的方法:
从jQuery绑定更改为常规JS绑定。 即来自
$this.focus(function () {....});
至
this.onfocus =function () {....};
在呈现事件时附加事件处理程序。
小提琴:
http://jsfiddle.net/sajjansarkar/GJvvu/
相关链接:
编辑
抱歉,我刚刚注意到您的评论,您想了解代码中的错误。 我可以很快告诉您一个错误,那就是jQuery和本机DOM方法的混合。 如果您致力于使用功能非常强大的库,则可以使用其所有功能,而不仅仅是您所了解的功能。
下面的代码使用事件委托(以解决您的焦点问题)和jQuery方法,比使用本机方法更简单地向表中添加一行。
如果要使用jQuery,则最好还是使用它:
var t = $('#myTable');
$(document)
.on('focus','#myTable input',function() {
$(this).css('background','red')
})
.on('click','#addRow',function() {
//create a new row
var
newIndex,
r = t.find('tr').eq(0).clone();
//append it to the table
r.appendTo(t);
//update newIndex - use it for later
newIndex = r.index();
//update the name/id of each of the inputs in the new row
r.find('input').each(function() {
var
el = $(this),
id = 'row'+newIndex+'col'+el.closest('td').index();
el.attr('id',id).attr('name',name);
});
});
您不需要遍历输入并将焦点处理程序绑定到每个输入,jQuery会自动收集与选择器匹配的所有DOM元素,并在每个输入上执行其焦点API函数:
更改此:
function addFocusListener() {
$("input").unbind();
$("input").each(function () {
var $this = $(this);
$this.focus(function () {
var newThis = $(this);
newThis.css('background-color', 'red');
});
});
}
对此
function addFocusListener() {
$('input')
.unbind()
.focus(function(){
$(this).css('background-color','red');
});
}
$("#addRow").live("click", function(){
addRowWithIncrementedIDs();
addFocusListener();
});
试试上面的代码...这应该工作..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.