列表项的单独函数

时间:2012-11-21 01:37:20

标签: javascript list onclick

我试图让这个代码以我点击第一项的方式工作,它将执行一项功能,当我点击第二项时,它将执行不同的功能。现在他们都去了同样的事情,我似乎无法把它分开。

 var list = [];

list[0] = ["zero"];
list[1] = ["one"];
list[2] = ["two"];
list[3] = ["three"];

function Make(){
for ( var i = 0; i < 4 ; i++ ) {
    var div = document.createElement("div");
    div.style.width = "10px";
    div.style.height = "10px";
    div.style.background = "white";
    div.style.color = "black";
    div.style.top = "0px";
    div.style.left = "0px";
    div.style.margin = "10px 10px auto";
    div.style.cursor = "pointer";
    div.innerHTML = list[i];
    !function(){
        var index = 0;
        div.onclick = function () { alert("this works"); };
    }();
    document.body.appendChild(div);
}
 }

1 个答案:

答案 0 :(得分:0)

你的意思是这样吗?

    <script type="text/javascript">
        var list = [];

        list[0] = ["zero"];
        list[1] = ["one"];
        list[2] = ["two"];
        list[3] = ["three"];

        function Make(){
            for ( var i = 0; i < 4 ; i++ ) {
                var div = document.createElement("div");
                div.style.width = "10px";
                div.style.height = "10px";
                div.style.background = "white";
                div.style.color = "black";
                div.style.top = "0px";
                div.style.left = "0px";
                div.style.margin = "10px 10px auto";
                div.style.cursor = "pointer";
                div.innerHTML = list[i];
                !function(){
                    var index = 0;
                    div.onclick = function () { doSomething(this); };
                }();
                document.body.appendChild(div);
            }
        }

        function doSomething(element){
            var value = element.innerHTML;
            alert('clicked : '+ value);
            switch(value){
                case "zero":
                //Your code here
                break;
                case "one":
                //Your code here
                break;
            }
        }
        Make();
    </script>