js函数中的参数

时间:2015-09-18 11:52:48

标签: javascript html5

我有一张桌子,上面有3列显示卡片,like this,所以当我按下卡片时,警报会显示我的号码,但我不知道如何显示号码,我试过href和onClick但我没有成功

html

<table id="gallery">
</table>

<script>generateTable3col();</script>

js

function generateTable3col(){
    var cards = [5,1,8,3,2,4,6];

    var rows = cards.length/3;
    var columns = 3;
    var rowNode, columnNode, link, img;
    var table = document.getElementById("gallery")
    var image = "backcard.png"

    for (var r=0;r<rows;r++){
        rowNode = document.createElement("tr");
        rowNode.style = "width:33%;";
        table.appendChild(rowNode);

        for(var c=0;c<columns; c++){
            columnNode =document.createElement("td");
            columnNode = table.appendChild(columnNode);

            link = document.createElement("a");
            link.setAttribute("hideNumber", cards[1*r+c]);

            //here I don't know how do
            link.href = "javascript:showCard(this)" //this is window object
            link.onclick = showCard(this); //execute when call the loop not when click

            img = document.createElement("img"); 
            img.style = "width: 100%;"
            img.src = image;

            link.appendChild(img);

            columnNode.appendChild(link);

        }
    }
}

//How?
function showCard(element){
    alert("card is: " + element.getAttribute("hideNumber")); //element is object window, not <a> element
}

1 个答案:

答案 0 :(得分:0)

而不是这一行:

link.onclick = showCard(this);

使用此:

link.onclick = function() { showCard(this); };

这里的不同之处在于,在第一种情况下,showCard(this);会立即执行。在第二种情况下,您将一个函数分配给onclick,只有在点击发生后才会执行。