获取具有等于变量的属性的元素的属性 [英] Get an attribute of an element that have an attribute that is equal a variable

查看:53
本文介绍了获取具有等于变量的属性的元素的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设我有这个:

<a href="/index" data-title="Home">LINK</a>
<a href="/page2" data-title="Another Page">LINK</a>

,我必须从a标记获得data-title,该标记的href等于location.pathname.

and I have to get the data-title from the a tag that has a href that is equal to the location.pathname.

我该如何使用jQuery?

How do I do this with jQuery?

推荐答案

使用以下代码:

$('a[href="' + location.href + '"]').attr('data-title')

请参见下面的工作代码示例,但将location.href替换为/index以显示代码片段效果很好:

See working code sample below, but location.href replaced to /index to show that snippet works well:

alert($('a[href="' + '/index' + '"]').attr('data-title'))

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="/index" data-title="Home">LINK</a>
<a href="/page2" data-title="Another Page">LINK</a>

这篇关于获取具有等于变量的属性的元素的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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