Internet Explorer是否有解决方法来实现'this‘javascript关键字提供的功能,以获取触发事件的dom元素?
我的问题场景是:在html表单中有数量可变的文本字段,例如
<input type="text" id="11"/>
<input type="text" id="12"/>
。。
我需要为每个文本字段处理"onchange“事件,而处理依赖于触发该事件的字段的”id“。到目前为止,我知道我的选择是: 1)为每个文本字段附加一个专用的事件处理程序。所以如果我有n个字段,我就有n个不同的函数,如下所示:
<input type="text" id="11" onchange="function11();"/>
<input type="text" id="12" onchange="function12();"/>
但是文本字段是动态添加和删除的,所以更好的方法是使用一个泛型函数。
2)使用'this‘关键字,如:
<input type="text" id="11" onchange="functionGeneric(this);"/>
<input type="text" id="12" onchange="functionGeneric(this);"/>
但此选项不适用于Internet Explorer。
有没有人能建议一种变通方法,让它在IE中工作,或者其他一些可以在这里应用的解决方案?谢谢。
发布于 2010-04-11 20:51:41
我不能重现你的问题。以下是基于评论中的最新信息的SSCCE:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2618458</title>
<script>
function functionGeneric(id) {
alert(id); // Shows either 11 or 12 correctly.
}
</script>
</head>
<body>
<input type="text" id="text_11" onchange="functionGeneric(this.id.split('_')[1]);"/>
<input type="text" id="text_12" onchange="functionGeneric(this.id.split('_')[1]);"/>
</body>
</html>
它在我这里的所有主要浏览器中都工作得很好。你的实际问题出在别的地方。在您提出更多细节或更好的SSCCE之前,它是在暗中寻找根本原因。
发布于 2010-04-11 19:55:52
第二个选项可能不起作用,因为元素ID必须以字母或下划线字符开头(至少根据规范)。
我会选择这样的东西:
// make the ids start with a word, like "foo", followed by "_", followed by a number
$("input[id^='foo_']").change(function() {
doSomething(this.id.split("_")[1]); // extract the number, pass to function
});
这将为ID为starting with 'foo‘的所有输入附加一个更改处理程序,并将数字从ID中分离出来,以传递给处理该数字的泛型函数。
https://stackoverflow.com/questions/2618458
复制