2013-10-28 119 views
14

所以我创建了一个使用Javascript和jQuery的表格,并且我希望它能够在您单击表格第一行上的td时,该列中其余的td下拉。让我试着通过显示我的代码来解释它。下面是我的javascript:jQuery .click功能不能在< td >标签上工作?

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的隐藏除TD在.row0,如果你单击.row0 .columni中的td,然后出现所有的.columni中的td。参数“的高度”是仅仅指刚一个阵列,例如,它可以是

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

和它会造成使用这些词表,headerOne和headerTwo将是在第一行中,someTd和anotherTd将在第二排。

现在,当我尝试在我的document.ready函数中添加点击功能,像这样

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

,然后调用它像这样

$(document).ready(function() { 

    createTr(heights); 
    animation(); 
}); 

它不会,当我做任何事点击一个td。怎么来的?

回答

30

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

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

从网址:

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

hm你是什么意思#newTabletbody?我试过$(“#newTable”),并且没有工作。 – user2719875

+0

对不起,这是一个错字。你可以尝试$('body')。on('点击,如果这似乎不起作用 – Churchill

+0

hm $('body')。on('click'也不起作用。我把所有的代码在函数动画中,就像函数动画(){$('body')。on('click','td',function(){alert('clicked');});} - 但是它似乎仍然没有工作 – user2719875

3

尝试这样的:

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

hm,似乎不工作) – user2719875

+1

如果你删除额外的'('后' td',那么它只有当我把它放在$(document).ready(函数 – user2719875

+0

哦,是的!!谢谢指出:)之前,它才能工作。 –

1

试试这个

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

'td'后是否应该有额外的括号,(?因为发布答案的其他用户也做了同样的事情,并且没有关闭在该函数之前出现在他“td”之后的那个括号。 – user2719875

+0

对不起,这是一个错字 –

+1

但没关系,这个作品和其他答案($('body')。on)也适用,只要我把它放在$(document).ready(function ..... thanks。 – user2719875

0

此代码工作得很好:

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

我喜欢这个.-

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