0

このコードを、アイテム1をクリックすると1つの機能を実行し、アイテム2をクリックすると別の機能を実行するように機能させようとしています。今のところ、それらはすべて同じものに行き、私はそれを引き離すことができないようです。

 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);
}
 }
4

1 に答える 1

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>
于 2012-11-21T01:44:50.427 に答える