找到包含单词的特定链接并添加到数组中

find specific links that contain a word and add to array

本文关键字:添加 链接 数组 包含单      更新时间:2023-09-26

我正试图在页面上搜索包含单词playgame的链接。如果他们找到了,那么我将他们添加到一个数组中。之后,从数组中选择一个随机值并使用window.location。我的问题是它说我的indexof是未定义的。我不确定这到底意味着什么,因为我仍在学习使用javascript的这一功能。

链接示例

<a href="playgame.aspx?gid=22693&amp;tag=ddab47a0b9ba5cb4"><img src="http://games.mochiads.com/c/g/running-lion-2/_thumb_100x100.jpg"></a>

javascript

var gameLinks = document.getElementsByTagName("a");
if (gameLinks.href.indexOf("playgame") != -1) {
    var links = [];
    links.push(gameLinks.href);
    var randomHref = links[Math.floor(Math.random() * links.length)];
    window.location = randomHref;
}

我的问题是它说我的索引是未定义的

不是indexOf,你调用它的东西。gameLinksNodeList,它没有href属性。您需要循环浏览列表的内容,以查看单个元素的href属性。例如:

var index, href, links, randomHref, gameLinks;
gameLinks = document.getElementsByTagName("a");
// Loop through the links
links = [];
for (index = 0; index < gameLinks.length; ++index) {
    // Get this specific link's href
    href = gameLinks[index].href;
    if (href.indexOf("playgame") != -1) {
        links.push(href);
    }
}
randomHref = links[Math.floor(Math.random() * links.length)];
window.location = randomHref;

更多探索:

  • DOM2核心
  • DOM2 HTML
  • DOM3核心
  • HTML5 Web应用程序API