gpt4 book ai didi

jquery - 查找具有特定字符串的所有 id

转载 作者:行者123 更新时间:2023-12-01 03:20:51 25 4
gpt4 key购买 nike

我试图获取页面上所有链接的所有 href 标签,并将它们放入一个数组中。我有以下代码,但是当我检查控制台时,出现错误 Uncaught TypeError: Object has no method 'attr' 我不确定从这里该去哪里。有什么想法吗?

代码

function videoLinks() {
var videoLinks = $("a[id^=a_l_]").each(function() {
var linkArray = jQuery.makeArray(videoLinks);
console.log(linkArray.attr("href"));
});
}

最佳答案

$.makeArray 返回 native JavaScript 数组,而不是 jQuery 对象。 native JavaScript 数组没有像 .attr() 这样的 jQuery 方法。这开始有意义了吗?

通过videoLinks$.makeArray根本没有意义,因为您要么传递函数 videoLinks ,或局部函数 videoLinks已经是一个 jQuery 对象。所以,我认为这更符合您想要做的事情:

function videoLinks() {
$("a[id^=a_l_]").each(function() {
console.log(this.href);
});
}

这将记录 href每个 <a> 的属性具有 id 的元素以 'a_l_' 开头。也许您想构建一个由 href 组成的数组属性而不是记录它们。然后你会使用 .map() .get() :

function videoLinks() {
var hrefs = $("a[id^=a_l_]").map(function() {
return this.href;
}).get(); // ← note the .get() call
}

my ultimate goal is to return one of the links at random

那么你就快到了。 Just get a random element from the hrefs array :

function videoLinks() {
var hrefs = $("a[id^=a_l_]").map(function() {
return this.href;
}).get(); // ← note the .get() call

var randHref = hrefs[Math.floor(Math.random() * hrefs.length)];
console.log(randHref);
}

关于jquery - 查找具有特定字符串的所有 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10183770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com