How can I get the ID of an element using jQuery?

后端 未结 19 2596
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 11:57

Why doesn\'

相关标签:
19条回答
  • 2020-11-22 12:31

    This will finally solve your problems:

    lets say you have many buttons on a page and you want to change one of them with jQuery Ajax (or not ajax) depending on their ID.

    lets also say that you have many different type of buttons (for forms, for approval and for like purposes), and you want the jQuery to treat only the "like" buttons.

    here is a code that is working: the jQuery will treat only the buttons that are of class .cls-hlpb, it will take the id of the button that was clicked and will change it according to the data that comes from the ajax.

    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">    </script>
    <script>
    $(document).ready(function(){
    $(".clshlpbtn").on('click',function(e){
    var id = $(e.target).attr('id');
     alert("The id of the button that was clicked: "+id);
    $.post("demo_test_post.asp",
        {
          name: "Donald Duck",
          city: "Duckburg"
        },
        function(data,status){
    
        //parsing the data should come here:
        //var obj = jQuery.parseJSON(data);
        //$("#"+id).val(obj.name);
        //etc.
    
        if (id=="btnhlp-1")
           $("#"+id).attr("style","color:red");
        $("#"+id).val(data);
        });
    });
    
    
    
    
    });
    </script>
    </head>
    <body>
    
    <input type="button" class="clshlpbtn" id="btnhlp-1" value="first btn">    </input>
    <br />
    <input type="button" class="clshlpbtn" id="btnhlp-2" value="second btn">    </input>
    <br />
    <input type="button" class="clshlpbtn" id="btnhlp-9" value="ninth btn">    </input>
    
    </body>
    </html>
    

    code was taken from w3schools and changed.

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