I would like to pass variable from a button to an event handler, but I don't know how what's the right way to do that. Both line x and line y are no good. But I need something like that.

in html head

window.onload = function()
{
    var myButton = document.getElementsByTagName("button");

    for (var i = 0; i < myButton.length; i++)
    {
        myButton[i].onclick = function()        // <-- line x
        {                
            alert(myButton[i].data1);           // <-- line y
        }
    }
}

in html body

<button type = "button" data1 = "John" data2 = "52">Click Me</button>
<button type = "button" data1 = "Peter" data2 = "26">Click Me</button>
<button type = "button" data1 = "Mary" data2 = "44">Click Me</button>
有帮助吗?

解决方案

Take a look at this JSFiddle example I just put together: http://jsfiddle.net/BshLK/1/

The problem with your code sample is that i is undefined by the time your event handler runs as it's only has it's value whilst the loop is running. To correct it, firstly you need to access the element you've called the event on and secondly you need to get use getAttribute() to get the attribute value.

其他提示

From your onload event I'm guessing you're not using jquery, but if you don't mind jquery I'd take a look at the data() method. You can do things like

$(function(){
    $("#button1").data("name", "value"); //your example would pass ("data","abcdefg");
    //Click handler.
    $("#button1").click(function(o,e){
         alert(o.data("name")); // alerts out "value"
    }
}

Then you can access that data using a selector to that element.

Link to the documentation

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top