javascript not working on dynamically added tabs

后端 未结 4 696
执笔经年
执笔经年 2021-01-26 06:01

I am facing a strange bug at the moment, involving javascript. I have used jquery ui tabs to dynamically add and remove tabs in my website, the content of the tab contains two b

相关标签:
4条回答
  • 2021-01-26 06:29

    use on delegated events...

    $(document).on("mouseenter", "#butt", function () {
      $(this).css("visibility","hidden");
    });
    
    $(document).on("mouseleave", "#butt", function () {
      $(this).css("visibility","visible");
    });
    

    you can read through this post if you want to know more about on direct and delegated event

    it is better if you delegate it to closest static element that is present in the document rather than to document or body for better performance

    0 讨论(0)
  • 2021-01-26 06:30

    You are binding the event on document load and adding button after the binding the event. So event will not bind with the element which added later.
    You should bind event after adding buttons.

    0 讨论(0)
  • 2021-01-26 06:35

    with reference to your fiddle...

    $("#butt").mouseenter(function () {
         $("#butt").css("visibility", "hidden");
     })
    

    it should be like this

    $jQuery.on("mouseenter","#butt",function () {
         $("#butt").css("visibility", "hidden");
     });
    

    Same goes for other elements which you know are going to be added at runtime.

    0 讨论(0)
  • 2021-01-26 06:37

    That's because mouseenter and mouseleave only work for items that exist in the DOM on page load

    You need to use a delegated event: on for jQuery 1.7+, or delegate for earlier versions.

    Try this (on):

    $("body").on("mouseenter", "#butt", function () {
        $(this).css("visibility","hidden");
    });
    
    $("body").on("mouseleave", "#butt", function () {
        $(this).css("visibility","visible");
    });
    

    Or this for pre-1.7 (delegate):

    $("body").delegate("#butt", "mouseenter", function () {
        $(this).css("visibility","hidden");
    });
    
    $("body").delegate("#butt", "mouseleave", function () {
        $(this).css("visibility","visible");
    });
    
    0 讨论(0)
提交回复
热议问题