简体   繁体   中英

In a for loop how to pass parameter of function invoked by document.getElementById('').onClick

When I click on the div element I want to alert the id of div I clicked on. But on all the div elements it is alerting the last value of array ie 'e1'.

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body  onload="populate();">
    <script type="text/javascript">
    function populate() {

        var divArray = ["a1", "b1", "c1", "d1", "e1"];
        for (var x in divArray) {
            if (divArray[x] === 'a1')
                document.getElementById(divArray[x]).innerHTML = "aaaaa";
            else
                document.getElementById(divArray[x]).innerHTML = "Common";

            document.getElementById(divArray[x]).onclick = function() {
                getDiv(divArray[x]);
            };
        }
    }

    function getDiv(x)
    {
        alert(x);
    }

    </script>
    <div id="a1"></div>
    <div id="b1"></div>
    <div id="c1"></div>
    <div id="d1"></div>
    <div id="e1"></div>

</body>
</html>

Your x is not the x you're hoping for. This might help.

// ...
document.getElementById(divArray[x]).onclick = (function(n) {
    return function() {
        getDiv(divArray[n]);
    };
}(x));
// ...

如果要返回被单击元素的ID,请用getDiv(this.id)替换getDiv(divArray[x])

This is because your for-loop has already ended by the time you actually click the div, so x is whatever it was when the loop ended. To fix this, you need to call getDiv(this.id);

Try passing the click event (e) into your click handler

        document.getElementById(divArray[x]).onclick = function(e) {
            console.log(e.toElement.id);
        };

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