Jquery .on versus .live

前端 未结 4 464
梦谈多话
梦谈多话 2020-12-09 15:58

I know that .live() is now deprecated but I cannot seem to change it and keep the functionality.

I just have a quick question about the

相关标签:
4条回答
  • 2020-12-09 16:27

    Ensure that the selected element (the th/tr) exists when the page is loaded initially. The new .on won't work if this selector is added later to the DOM.

    Try

    $('body').on('click', 'thesSelectorForYourTriggerElement', function(){
        //callback
    });
    
    0 讨论(0)
  • 2020-12-09 16:33

    I somehow guess that you are adding tr elements into your table, not th.

    $('table').on("click", "tr th", function(){});
    
    0 讨论(0)
  • 2020-12-09 16:35

    Try this:

    $('table tr th').live("click", function() {
    

    should be

    $(document).on("click", "table tr th", function() {
    

    That is how you would mimic the .live call exactly. You could of course limit your selector from document to something more meaningful based on your DOM structure.

    Edit:

    Just to clarify, in your example, you are required to use $(document).on(... because the table doesn't have any parents and is replaced during the life of your page.

    0 讨论(0)
  • 2020-12-09 16:44

    The on() function requires a syntactical update, you should alter your code to:

    $('body').on("click", "table tr th", function()...
    

    Check out this article for more info: http://www.andismith.com/blog/2011/11/on-and-off/

    0 讨论(0)
提交回复
热议问题