![](/img/trans.png)
[英]How to write jquery to find html element id attribute value and set that value to same html class attribute?
[英]jquery equivalent to find value of certain attribute on an html element
<div custom-attribute="somevalue"></div>
var x = document.getElementsByTagName("DIV")[0].getAttribute("custom-attribute");
console.log(x); //somevalue
现在我知道它的第0格,但它可以在任何随机div上。
是否存在与上述等效的Jquery以实现获取elements属性的值?
使用.attr()
函数。
var x = $("div").attr("custom-attribute"); console.log(x);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div custom-attribute="somevalue"></div>
jQuery有一个.attr
方法,它将执行您想要的操作:
// Old way: var x = document.getElementsByTagName("DIV")[0].getAttribute("custom-attribute"); console.log(x); //somevalue // JQuery way: var y = $("div").attr("custom-attribute"); console.log(y) // somevalue
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div custom-attribute="somevalue"></div>
jQuery选择器采用与CSS选择器完全相同的语法,因此请使用属性选择器来定位元素,然后使用.attr()
方法提取属性值。
var x = $("div[custom-attribute]"); console.log(x.attr("custom-attribute")); //somevalue
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div custom-attribute="somevalue"></div>
但是,请知道自定义属性是无效的HTML,除非它们采用data-customName
的形式,在这种情况下,您仍将以相同的方式选择元素,但是您将使用JQuery的.data()
访问data-*
属性。 方法 ,如下所示:
var x = $("div[data-custom-attribute]"); console.log(x.data("customAttribute")); //somevalue
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div data-custom-attribute="somevalue"></div>
并且,仅出于参考目的,您的原始原始JavaScript代码实际上应该首先非常相似,因为.getElementsByTagName()
将扫描整个文档,当您只查找一个文档时,您不想这样做。元件。 此外,它还会返回“活动”节点列表,从而影响性能。
var x = document.querySelector("div[data-custom-attribute]"); console.log(x.dataset.customAttribute); //somevalue
<div data-custom-attribute="somevalue"></div>
相当于document.getElementByTagName("name")
是$("name")
。
用[i]
索引结果的等效项是.eq(i)
。
.getAttribute("attr")
的等效项是`.attr(“ attr”)。
所以整个事情是:
var x = $("div").eq(0).attr("custom-attribute");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.