Javascript 无法将事件侦听器附加到IE8中动态创建的元素
概述: 当我点击一个按钮时,我想Javascript 无法将事件侦听器附加到IE8中动态创建的元素,javascript,jquery,events,internet-explorer-8,Javascript,Jquery,Events,Internet Explorer 8,概述: 当我点击一个按钮时,我想 在表的末尾插入新行 从表的第一行复制单元格和内容 为单元格中的元素指定唯一的ID 将焦点事件侦听器分配给页面中的所有输入 问题: 事件处理程序没有在IE8中的正确元素上触发。例如,如果我关注表中的最后一个输入,则第一个输入将突出显示 澄清: 这在IE10中有效,Chrome 在我的目标浏览器IE8中不起作用 我知道很多方法 我的目标不是找到解决办法,而是 在给定的代码中,理解我的错误是什么 示例代码只是问题的快速简化版本。我不是在要求与问题无关的代码优化
- 在表的末尾插入新行
- 从表的第一行复制单元格和内容
- 为单元格中的元素指定唯一的ID
- 将焦点事件侦听器分配给页面中的所有输入
- 这在IE10中有效,Chrome
- 在我的目标浏览器IE8中不起作用李>
- 我知道很多方法 我的目标不是找到解决办法,而是 在给定的代码中,理解我的错误是什么
- 示例代码只是问题的快速简化版本。我不是在要求与问题无关的代码优化
- 更改事件也不起作用
this.onfocus=function(){….}代码>
在呈现事件处理程序时附加它们
小提琴:
SO中的相关链接:
试试上面的代码。。。这应该会起作用。编辑
抱歉,我刚刚注意到您的评论,您希望了解代码中的错误。
我可以很快告诉您一个错误,那就是混合使用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');
});
}
如果从$this.focus开始更改(
to$this.onfocus=
解决了问题,问题就在那里,尽管我怀疑这只是你问题中的一个输入错误。jQuery的哪个版本?@KevinB好吧,我想知道问题出在哪里?为什么第一种方法不起作用?如果第二种方法起作用,那么$this不是jQuery对象,这就是第一种方法起作用的原因不起作用。但是看到你的代码,这不应该发生。@SLaks在1.7.1、1.9.1和1.10.2上试过,但它没有回答问题。这是一种很好的方法。感谢和+1的代码。但正如我提到的,这对我来说更像是一个知识问题,可以理解为什么我的代码不起作用。不过再次感谢:)
$("#addRow").live("click", function(){
addRowWithIncrementedIDs();
addFocusListener();
});
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);
});
});
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');
});
}