jQuery:如何获取 html 属性的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1845041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:15:13  来源:igfitidea点击:

jQuery: How to get the value of an html attribute?

jquery

提问by Andrew

I've got an html anchor element:

我有一个 html 锚元素:

<a title="Some stuff here">Link Text</a>

...and I want to get the contents of the title so I can use it for something else:

...我想获取标题的内容,以便我可以将其用于其他用途:

$('a').click(function() {
    var title = $(this).getTheTitleAttribute();
    alert(title);
});

How can I do this?

我怎样才能做到这一点?

回答by yoda

$('a').click(function() {
    var title = $(this).attr('title');
    alert(title);
});

回答by awgy

$('a').click(function() {
    var title = $(this).attr('title');
    alert(title);
});

回答by Josh Gibson

$(this).attr("title")

回答by rahul

You can simply use this.titleinside the function

您可以简单地this.title在函数内部使用

$('a').click(function() {
    var myTitle = $(this).attr ( "title" ); // from jQuery object
    //var myTitle = this.title; //javascript object
    alert(myTitle);
});

Note

笔记

Use another variable name instead of 'alert'. Alert is a javascript function and don't use it as a variable name

使用另一个变量名而不是 'alert'。Alert 是一个 javascript 函数,不要将其用作变量名

回答by Prince Patel

You can create function and pass this function from onclick event

您可以创建函数并从 onclick 事件传递此函数

<a onclick="getTitle(this);" title="Some stuff here">Link Text</a>

<script type="text/javascript">

function getTitle(el)
{
     title = $(el).attr('title');
     alert(title);
}

</script>

回答by Archis

Even you can try this, if you want to capture every click on the document and get attribute value:

即使你可以尝试这个,如果你想捕获文档上的每次点击并获取属性值:

$(document).click(function(event){
    var value = $(event.target).attr('id');
    alert(value);
});