javascript 类型错误:$(...)[1].attr 不是函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33023806/
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
TypeError: $(...)[1].attr is not a function
提问by Pav Sidhu
I have links set up like so:
我的链接设置如下:
HTML:
HTML:
<a href="www.example1.com" class="some-link">
<a href="www.example2.com" class="some-link">
<a href="www.example3.com" class="some-link">
<a href="www.example4.com" class="some-link">
I want to get the href
s that the <a>
tags contain. I tried to iterate through each link like so:
我想获得标签包含的href
s <a>
。我尝试像这样遍历每个链接:
Javascript / jQuery:
Javascript / jQuery:
for (x=0; x < 5; x++) {
link = $(".some-link")[x].attr("href");
console.log(link);
}
When I try this, I get the error TypeError: $(...)[x].attr is not a function
. What's the issue? Thanks.
当我尝试这个时,我收到错误TypeError: $(...)[x].attr is not a function
。有什么问题?谢谢。
回答by Pranav C Balan
You need to use eq()
here, since $(".some-link")[x]
returns dom object attr()
method can only use with jQuery object. So you nee to use eq(x)
or :eq()
eq()
此处需要使用,因为$(".some-link")[x]
返回 dom 对象的attr()
方法只能与 jQuery 对象一起使用。所以你需要使用eq(x)
或:eq()
for (x=0; x < 5; x++) {
link = $(".some-link").eq(x).attr("href");
console.log(link);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="www.example1.com" class="some-link">
<a href="www.example2.com" class="some-link">
<a href="www.example3.com" class="some-link">
<a href="www.example4.com" class="some-link">
<a href="www.example4.com" class="some-link">
or you can use each()
method instead
或者你可以改用each()
方法
$(".some-link").each(function(){
var link=$(this).attr("href");
console.log(link);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="www.example1.com" class="some-link">
<a href="www.example2.com" class="some-link">
<a href="www.example3.com" class="some-link">
<a href="www.example4.com" class="some-link">
<a href="www.example4.com" class="some-link">
or more simple way use attr()
with callback
或更简单的方式attr()
与回调一起使用
$(".some-link").attr("href",function(i,link){
console.log(link);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="www.example1.com" class="some-link">
<a href="www.example2.com" class="some-link">
<a href="www.example3.com" class="some-link">
<a href="www.example4.com" class="some-link">
<a href="www.example4.com" class="some-link">
回答by alexn
The [1]
indexer (equivalent to .get()
) does not return a jQuery element, but a DOM element. Try
该[1]
索引(相当于.get()
)不返回一个jQuery元素,但DOM元素。尝试
var link = $(".some-link").eq(x).attr("href");
As a side note, you probably want to declare your variable using var
.
作为旁注,您可能希望使用var
.