猿问

getElemntById里如何放变量?

        function $id(id)

            {return document.getElementById(id);};

        

        for(x = 1;x < 4;x++)

        {                

            $id("button_img_"+x).addEventListener("click",slide_button);    

        }

如上述代码,id需要被遍历,如何让document.getElementById("id")里的id为变量?

谢谢


慕容708150
浏览 645回答 1
1回答

小怪兽爱吃肉

你现在这样遍历没有问题呀,这样可以传一个变量id进去。function $id(id) {&nbsp; &nbsp; return document.getElementById(id);};for (x = 1; x < 4; x++) {&nbsp; &nbsp; (function(x){&nbsp; &nbsp; &nbsp; &nbsp; $id("button_img_" + x).addEventListener("click", function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert(x);&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }(x))}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答