jQuery .click 函数在 < td > 标签上不起作用

jQuery .click function not working on < td > tag?

本文关键字:标签 不起作用 td click 函数 jQuery      更新时间:2023-09-26

所以我正在使用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">

我希望它使所有 td 都被隐藏,除了 .row0 中的 td,如果您单击 .row0 .columni 中的 td,则会出现 .columni 中的所有 td。参数"heights"只是一个数组,例如,它可以是

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

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

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

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

然后在我的 document.ready 函数中调用它,如下所示

$(document).ready( function() {
    createTr(heights);
    animation();
});

当我点击TD时,它没有任何作用。怎么来了?

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

由于您是在创建 DOM 之后创建元素的。使用"on"选择器获取动态创建的精确元素。

从网址:

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

尝试如下:

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

试试这个

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

我喜欢这个。

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

这段代码工作得很好:

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

使用它来捕获 speifc tr 和 td 的点击事件;

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