2012-07-10 34 views
1

我试图搜索包含单词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; 
} 

回答

2

我的问题是,它说我的indexOf是不确定的

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; 

探索更多:

+0

谢谢是的,我忘了补充对于那些'var'变量秒。我更新了我的帖子。我测试你的代码,但数组只填充undefined字。这是否意味着“playgame”字符串没有找到? – 2012-07-10 08:21:57

+0

@ Mr.1.0 - 在T.J.的代码中,'links.push(gameLinks.href);'应该是'links.push(href);'。我编辑了T.J.的代码来纠正。 – jfriend00 2012-07-10 08:23:45

+0

非常感谢你的时间和帮助。我非常感谢。 – 2012-07-10 08:29:12

相关问题