简体   繁体   中英

How can I get IE's Javascript to implement the 'this' keyword functionality?

Is there a workaround for Internet Explorer to implement the functionality offered by 'this' javascript keyword to get the dom element that triggered the event?

My problem scenario is : I have a variable number of text fields in the html form, like

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

..

I need to handle the "onchange" event for each text field, and the handling is dependent on the 'id' of the field that triggered the event. So far I understand that my options are: 1) attach a dedicated event handler for each text field. so if I have n fields, i have n different functions, something like:

<input type="text" id="11" onchange="function11();"/>  
<input type="text" id="12" onchange="function12();"/>

but the text fields are added and removed dynamically, so a better way would be to have one generic function instead.

2) use the 'this' keyword like:

<input type="text" id="11" onchange="functionGeneric(this);"/>  
<input type="text" id="12" onchange="functionGeneric(this);"/>

But this option does not work with Internet Explorer.

Can anyone suggest a work around for getting it work in IE or some other solution that can be applied here? Thanks.

I can't reproduce your problem. Here's an SSCCE based on the latest information in comments:

<!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>

It works fine in all major browsers I have here. Your actual problem lies somewhere else. Until you come up with more detail, or better, an SSCCE, it's shooting in the dark to the root cause.

The second option probably does not work because element IDs must start with alphabet or the underscore character (at least, according to the spec).

I would opt for something like this:

// 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
});

That will attach a change handler to all of your inputs with IDs starting with 'foo', and split the number out of the ID to pass to the generic function which works on the number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM