Javascript/jQuery - How do I obtain name of the class of clicked element?

前端 未结 6 1560
礼貌的吻别
礼貌的吻别 2020-12-16 00:27

I googled and googled and I concluded that it\'s very hard to get answer on my own.

I am trying to use jquery or JavaScript to get a property of clicked element. I c

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-16 00:54

    In jQuery, if you attach a click event to all

    tags (for example), you can get it's class like this:

    Example: http://jsfiddle.net/wpNST/

    $('div').click(function() {
        var theClass = this.className;  // "this" is the element clicked
        alert( theClass );
    });
    

    This uses jQuery's .click(fn) method to assign the handler, but access the className property directly from the DOM element that was clicked, which is represented by this.

    There are jQuery methods that do this as well, like .attr().

    Example: http://jsfiddle.net/wpNST/1/

    $('div').click(function() {
        var theClass = $(this).attr('class');
        alert( theClass );
    });
    

    Here I wrapped the DOM element with a jQuery object so that it can use the methods made available by jQuery. The .attr() method here gets the class that was set.

提交回复
热议问题