jQuery .click函数无法正常工作< td>标签?

时间:2013-10-28 17:24:53

标签: javascript jquery html html-table jquery-click-event

所以我正在使用Javascript和jQuery创建一个表,我想要它,这样当你点击表格第一行的td时,那个列中其余的td就会下拉。让我试着通过展示我的代码来解释它。这是我的Javascript:

function createTr (heights) { //heights is just an array of words
    for (var h=0; h<heights.length; h++) { 
        var theTr = $("<tr>", { id: "rowNumber" + h});
        for (var i=0; i<heights.length-3; i++) { 
            theTr.append($("<td>", { "class": "row"+h + " column"+i,
                                     html: heights[h][i]
                                   }));
        }
        $('#newTable').append(theTr); // append <tr id='rowNumber0'> to the table (#newTable), which is written in the html
    }
}

这基本上创建了td,每个td类似于这种格式

<td class="rowh columni">

我想要它以便除了.row0中的td之外都隐藏所有td,如果单击.row0 .columni中的td,则会出现.columni中的所有td。参数'heights'是一个数组,例如,它可以是

var heights = [['headerOne', 'headerTwo'], ['someTd', 'anotherTd'],];

它将使用这些单词创建一个表,headerOne和headerTwo将在第一行,someTd和anotherTd将在第二行。

现在,当我尝试添加像这样的点击功能时

function animation() {
    $('td').click( function() {
        alert('clicked');
    });
}

然后在我的document.ready函数中调用它

$(document).ready( function() {

    createTr(heights);
    animation();
});
当我点击一个td时,它没有做任何事情。怎么样?

6 个答案:

答案 0 :(得分:43)

http://api.jquery.com/on/

因为您在创建DOM后创建元素。使用“on”选择器获取动态创建的精确元素。

来自网址:

   $("#newTable").on("click", "td", function() {
     alert($( this ).text());
   });

答案 1 :(得分:6)

试试这样:

$('body').on('click','td', function() {
        alert('clicked');
    });

答案 2 :(得分:1)

试试这个

function animation() {
    $(document).on('click','td',function() {
    alert('clicked');
    });
}

答案 3 :(得分:0)

这段代码很好用:

$(document).ready(function(){
    $("td").click(function(){
        if(this.title!=""){
            alert(this.title);
        }
    });
});

答案 4 :(得分:0)

我喜欢这个.-

 $("#table tr").click(function(){
    console.log(this);
});

答案 5 :(得分:0)

使用此功能捕获spesifc tr和td的点击事件;

$('#table_id').on('click', 'tr.statusP td:first-child', function () {
                    alert('clicked');
                });
相关问题