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

前端 未结 3 1841
猫巷女王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:44

    Try this:

    JavaScript

    $(function () {
        $('div').click(function () {
            var elem = $(this);
            alert('Class: ' + elem.attr('class'));
            alert('Id: ' + elem.attr('id'));
            alert('Name: ' + elem.attr('name'));    
        });​​​​
    });
    

    HTML

    CSS

    ​div {
        width: 100px;
        height: 100px;
        border: 1px solid black;
    }​
    

    JSfiddle: http://jsfiddle.net/54ynV/

    In the script above we're attaching to the click event of every div on the page $('div').click.... In the callback we're getting it's attributes.

提交回复
热议问题