How can I get id,class or name attr an element with jquery

前端 未结 3 1855
猫巷女王i
猫巷女王i 2021-01-06 09:07

I\'m new in jquery. How can I get name,ID or class name an element with jquery.I\'m trying as;

3条回答
  •  爱一瞬间的悲伤
    2021-01-06 09:42

    Firstly using jQuery you should attach click() handlers rather than use antiquated onclick attributes. Then you can use the this keyword in the manner you have in your function.

    Try this:

    $(function() {
        $("div").click(function() {
            var name = this.name;
            var cls = this.className;
            var id= this.id;
    
            alert("Name: " + name + " / Class: " + cls + " / Id: " + id);
        });
    });
    

    Example fiddle

    The attributes you've selected are all available through POJS, you could also convert this to a jQuery object to get other attributes, for example:

    var title = $(this).attr('title');
    var myattribute = $(this).data('myattribute'); // using HTML5: 

提交回复
热议问题