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

时间:2022-11-26 23:40:06

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?

我该怎么做呢?

6 个解决方案

#1


7  

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

#2


1  

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

#3


1  

$(this).attr("title")

#4


1  

You can simply use this.title inside the function

你可以用这个。标题里面的函数

$('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函数,不用作变量名

#5


0  

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);
});

#6


0  

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>

#1


7  

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

#2


1  

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

#3


1  

$(this).attr("title")

#4


1  

You can simply use this.title inside the function

你可以用这个。标题里面的函数

$('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函数,不用作变量名

#5


0  

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);
});

#6


0  

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>