如何使用 jquery 获取元素的 id、class 或 name attr [英] How can I get id,class or name attr an element with jquery

查看:85
本文介绍了如何使用 jquery 获取元素的 id、class 或 name attr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 jquery 的新手.如何使用 jquery 获取元素的名称、ID 或类名.我正在尝试;

<div id="idName" onclick="getName();"></div><div name="attrName" onclick="getName()"></div>函数 getName(){attrName = $(this).attr("name");警报(属性名称);}

但不起作用

解决方案

首先使用 jQuery,您应该附加 click() 处理程序,而不是使用过时的 onclick 属性.然后您可以按照您在函数中的方式使用 this 关键字.

试试这个:

<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("姓名:" + 姓名 + "/班级:" + cls + "/Id:" + id);});});

小提琴示例

你选择的属性都可以通过POJS获取,你也可以将this转成jQuery对象来获取其他属性,例如:

var title = $(this).attr('title');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>

这篇关于如何使用 jquery 获取元素的 id、class 或 name attr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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