如何让IE的Javascript实现'this'关键字功能?

时间:2010-04-11 19:51:09

标签: javascript jquery html event-handling this

Internet Explorer是否有解决方法来实现'this'javascript关键字提供的功能,以获取触发事件的dom元素?

我的问题场景是: 我在html表单中有可变数量的文本字段,比如

<input type="text" id="11"/>  
<input type="text" id="12"/>

...

我需要为每个文本字段处理“onchange”事件,并且处理依赖于触发事件的字段的“id”。 到目前为止,我知道我的选择是: 1)为每个文本字段附加专用的事件处理程序。所以,如果我有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中运行或者可以在这里应用的其他解决方案吗? 感谢。

2 个答案:

答案 0 :(得分:3)

我无法重现你的问题。根据评论中的最新信息,这是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之前,它是在黑暗中射击的根本原因。

答案 1 :(得分:1)

第二个选项可能不起作用,因为元素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中分离出来以传递给处理该数字的泛型函数。