我怎样才能得到ID,类或名称属性与jQuery的元素 [英] How can I get id,class or name attr an element with jquery

查看:89
本文介绍了我怎样才能得到ID,类或名称属性与jQuery的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是jquery的新成员。

 < div class = classNameonclick =getname();>< / div> 
< div id =idNameonclick =getName();>< / div>
< div name =attrNameonclick =getName()>< / div>

函数getName(){
attrName = $(this).attr(name);
alert(attrName);
}

但无效

解决方案首先使用jQuery,你应该附加 click code>属性。然后,您可以按照您在函数中使用的方式使用 this 关键字。 试试这个:

 < div class =className>< / div> 
< div id =idName>< / div>
< div name =attrName>< / div>



$(function() {
$(div)。click(function(){
var name = this.name;
var cls = this.className;
var id = this.id ;

alert(Name:+ name +/ Class:+ cls +/ Id:+ id);
});
});

示例小提琴



您选择的属性都可以通过POJS使用,也可以将 到一个jQuery对象来获得其他属性,例如:

  var title = $(此).attr( '标题'); 
var myattribute = $(this).data('myattribute'); //使用HTML5:< div data-myattribute =foo>< / div>


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

<div class="className" onclick="getname();"></div>
<div id="idName" onclick="getName();"></div>
<div name="attrName" onclick="getName()"></div>

function getName(){
attrName = $(this).attr("name");
alert(attrName);
}

but doesn't work

解决方案

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:

<div class="className"></div>
<div id="idName"></div>
<div name="attrName"></div>

$(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: <div data-myattribute="foo"></div>

这篇关于我怎样才能得到ID,类或名称属性与jQuery的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆