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
195 views
in Technique[技术] by (71.8m points)

click event not triggered at the first click in jquery

I have a main.php inside which another page (page1.php) is being called embedded in a div. I am dynamically updating the a table in page1 when the page1.php is loaded.

Now when I call a function on the click event of the table the function is called but the control doesn't enters in the click event of the table which I have called inside the function. However clicking the second time onwards the control enters and works fine.

Following is the function in the js file

function highlight_table()
{
$(#table tr).click(function(){
alert("here");
});
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Make sure you are calling this function when the DOM is loaded so that the event handler is attached the first time:

$(function() {
    highlight_table();
});

If the table is not present when the DOM is loaded but is later added using AJAX you might need to call this function in the success handler of your AJAX request.

Also you might need to use the .live() function so that when the table is updated the click handler is preserved (if needed):

$('#table tr').live('click', function() {
    alert('here');
});

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

...