放在哪里...或者我应该使用.click()

时间:2014-10-22 08:18:28

标签: javascript jquery onclick click

我正在尝试为记忆游戏制作一个基本的GUI。关于如何使用onclick显示每个td的id,我感到很遗憾。我不认为我正在考虑var cellID发生的事情。其余的工作。看评论。

function cid(){alert(cellID);}//**<-- I feel like this shouldn't be here.** 

function makeBoard(h,w){
var $tab, $row, $cell;

   $tab = $('<div>')
       .attr('id','game')
       .appendTo('#memorygame');


       for(var i = 0; i < h; i++){
            $row = $('<tr>')
            .appendTo($tab);
            for(var j = 0; j <w; j++){
                 var cellID = ('row'+i+'col'+j)
                 $cell = $('<td onclick="cid()">')//**<-- this isn't working**
                 .attr('id',cellID)
                 .appendTo($row);
            }
         } 
     }
         $(makeBoard);

2 个答案:

答案 0 :(得分:2)

$cell = $('<td>')
    .attr('id',cellID)
    .click(function(){
        alert($(this).attr('id'));
    })
    .appendTo($row);

或者您可以使用

代替警报
$('#whereyouwanttodisplay').html($(this).attr('id'));

答案 1 :(得分:0)

我不认为你在jquery函数中使用了一个有效的选择器。首先尝试创建td,然后像这样添加attribut。 $('')。attr('onclick','cid()')

相关问题