Add and remove attribute with jquery

前端 未结 4 1121
北恋
北恋 2020-12-04 21:28

This is my buttons:



this is my JavaScript cod

相关标签:
4条回答
  • 2020-12-04 21:44

    Once you remove the ID "page_navigation" that element no longer has an ID and so cannot be found when you attempt to access it a second time.

    The solution is to cache a reference to the element:

    $(document).ready(function(){
        // This reference remains available to the following functions
        // even when the ID is removed.
        var page_navigation = $("#page_navigation1");
    
        $("#add").click(function(){
            page_navigation.attr("id","page_navigation1");
        });     
    
        $("#remove").click(function(){
            page_navigation.removeAttr("id");
        });     
    });
    
    0 讨论(0)
  • 2020-12-04 21:44

    First you to add a class then remove id

    <script type="text/javascript">
    $(document).ready(function(){   
     $("#page_navigation1").addClass("page_navigation");        
    
     $("#add").click(function(){
            $(".page_navigation").attr("id","page_navigation1");
        });     
        $("#remove").click(function(){
            $(".page_navigation").removeAttr("id");
        });     
      });
    </script>
    
    0 讨论(0)
  • 2020-12-04 21:47

    If you want to do this, you need to save it in a variable first. So you don't need to use id to query this element every time.

    var el = $("#page_navigation1");
    
    $("#add").click(function(){
      el.attr("id","page_navigation1");
    });     
    
    $("#remove").click(function(){
      el.removeAttr("id");
    });     
    
    0 讨论(0)
  • 2020-12-04 21:55

    It's because you've removed the id which is how you're finding the element. This line of code is trying to add id="page_navigation1" to an element with the id named page_navigation1, but it doesn't exist (because you deleted the attribute):

    $("#page_navigation1").attr("id","page_navigation1");
    

    Demo:

    If you want to add and remove a class that makes your <div> red use:

    $( '#page_navigation1' ).addClass( 'red-class' );
    

    And:

    $( '#page_navigation1' ).removeClass( 'red-class' );
    

    Where red-class is:

    .red-class {
        background-color: red;
    }
    
    0 讨论(0)
提交回复
热议问题