[英]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.