简体   繁体   English

在href中使用attr函数时出错

[英]Error using the attr function with href

I get the error undefined is not a function when running this code: 运行此代码时出现错误undefined is not a function

var links=$("li").find("a");//this works...has a length of 23
//then I run this
for(var i=0;i<links.length;i++){
  links[i].attr("href");//this does not work
}

What can I do to obtain to get the href property from the link? 我该怎么做才能从链接中获取href属性?

The elements of a jQuery object are DOM elements, not other jQuery objects, so they don't have jQuery methods. jQuery对象的元素是DOM元素,而不是其他jQuery对象,因此它们没有jQuery方法。 You can use the eq method to access jQuery-wrapped versions of those elements: 您可以使用eq方法访问这些元素的jQuery包装版本:

for(var i=0;i<links.length;i++){
    href = links.eq(i).attr("href");
}

Or just access the property directly: 或者直接访问属性:

for(var i=0;i<links.length;i++){
    href = links[i].href;
}

In your example code you're not actually doing anything with the value though so you may want to sort that out too. 在示例代码中,您实际上并未对该值做任何事情,因此您可能也想对它进行整理。

You should simply try : 您应该尝试:

$("li a").each(function(){
  console.log($(this).attr('href'));
});

Or fix your code to create a jquery object to be able to use attr function : 或修复您的代码以创建一个能够使用attr函数的jquery对象:

for(var i=0;i<links.length;i++){
  $(links[i]).attr("href");
}

Or simply use href : 或者直接使用href:

  links[i].href;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM