开发者

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

开发者 https://www.devze.com 2022-12-13 17:07 出处:网络
I\'ve got an html anchor element: &l开发者_StackOverflowt;a title=\"Some stuff here\">Link Text</a>

I've got an html anchor element:

&l开发者_StackOverflowt;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?


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


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


$(this).attr("title")


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


You can create function and pass this function from onclick event

<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>


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

精彩评论

暂无评论...
验证码 换一张
取 消