Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

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

So I am creating a table using Javascript and jQuery, and I want it so that when you click the td's on the first row of the table, then the rest of the td's in that column drop down. Let me try to explain it by showing my code. Here is my 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
    }
}

This basically creates td's and each td is similar to this format

<td class="rowh columni">

I want it so that all td's are hidden except for the td's in .row0 and if you click the td in .row0 .columni, then all td's in .columni appear. The parameter 'heights' is jsut an array, for example, it can be

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

and it would create a table using those words, headerOne and headerTwo would be in the first row, someTd and anotherTd would be in the second row.

Now, when I try to add a click function like so

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

and then call it in my document.ready function like so

$(document).ready( function() {

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

it doesn't do anything when I click a td. How come?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Since you are creating the elements after the DOM has been created. Use the "on" selector to get the precise element that is dynamically created.

From the URL:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...