douchen4534 2013-03-28 04:15
浏览 68
已采纳

为什么在向页面动态添加内容后,我的JS功能无法正常工作?

I have a javascript function that is defined in the beginning of my webpage. It is called when a row is clicked in my table.

here is my function:

    $(".info").click(function(){
        alert($(this).attr('movieid'));
    });

here is my what my table row looks like:

<tr class="info" movieid="123"><td>movie title</td></tr>

now that table is displayed when I first load the page, I can click the row and it will call the function correctly. I am trying to implement a search function for the table. I have the php script return table rows just like the one above, I add them to the table, but when I click the row that is returned from the php script, the javascript function isn't called. Does anyone know how I can accomplish this? I've had no luck.

EDIT

here is my function to get the search results:

$.ajax({
        type: "POST",
        url: "www.mysite.com/core/search.php",
        data: { q: search_string},
        cache: false,
        success: function(html){
            $("table#movies").fadeOut();
            $("div#results-container").fadeIn();
            $("div#results").fadeIn();
            $("div#results").html(html);
        }
});
  • 写回答

7条回答 默认 最新

  • duandu8707 2013-03-28 04:31
    关注

    You are adding the element dynamically so it is not registered when you set the click handler.

    $("body").on("click", ".info", function(e) {
       ...
    });
    

    body usually works but ideally you'd want a DOM element as close to your selector .info as possible.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?