简体   繁体   English

javascript参数输入错误的数字

[英]javascript argument get wrong number

I'm trying to create dynamically a menu in Javascript with a function with one argument in the onclick property using the code bellow: 我正在尝试使用以下代码在onclick属性中使用一个函数带有一个参数的函数在Javascript中动态创建菜单:

function createCameraMenu() {
    var nav = document.createElement('nav');
    var ul  = document.createElement('ul');
    ul.className = "menu";

    for (var i = 0; i < cameraID.length; i = i + 1) {
        var liField = document.createElement('li');
        var aField  = document.createElement('a');

        aField.textContent = "CAMERA " + i;

        aField.onclick = function() {
            hideImages(i);
        };

        li.appendChild(aField);
        ul.appendChild(li);
    }

    nav.appendChild(ul);
    document.body.appendChild(nav);
}

and the result should be the code bellow: 结果应该是下面的代码:

<nav>
    <ul class="menu" >
        <li><a href="#" onClick="hideImages(0)">CAMERA 1</a></li>
        <li><a href="#" onClick="hideImages(1)">CAMERA 2</a></li>
        <li><a href="#" onClick="hideImages(2)">CAMERA 3</a></li>                
    </ul>
</nav>

but after creating the menu, for any item clicked, the function hideImages(3) is executed. 但是在创建菜单之后,对于单击的任何项目,都会执行函数hideImages(3)。 For some reason, all my functions are created with the same argument (3), that is the value of "i" rejected in the for loop. 出于某种原因,我所有的函数都使用相同的参数(3)创建,即在for循环中拒绝的“ i”值。 There is no global var i in my code and I don't know why this is happening. 我的代码中没有全局变量,我也不知道为什么会这样。 This function is executed in a script tag in the head of the HTML file. 该功能在HTML文件开头的脚本标签中执行。

You need to use a closure , eg: 您需要使用闭包 ,例如:

for (var i = 0; i < cameraID.length; i = i++) {
        var liField = document.createElement('li');
        var aField  = document.createElement('a');

        aField.textContent = "CAMERA " + i;

        aField.onclick = (function(i){ return function() {
            hideImages(i);
        };})(i);

        li.appendChild(aField);
        ul.appendChild(li);
    }

Now for readability, you can use a referenced method instead: 现在为了提高可读性,您可以改用引用的方法:

aField.onclick = hideImages.bind(aField, i);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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