代码:
var links = document.getElementsByTagName('link');
var links_length = links.length;
for (var i = 0; i < links_length; i++)
{
if (links[i].getAttribute('rel').indexOf('test') !== -1)
{
//blabla
// but now I want to target for example... HREF attribute of link that got test in it's rel attribute... so
if (links[i].getAttribute('href').indexOf('test2') !== -1)
{
//blabla2
// but it doesn't work
// it won't give me href with test2 of the link with rel attribute with test. The code give my last link with href of test2... dunno why. Any ideas?
}
}
}
为什么我无法与rel='test'
和href='test2'
建立正确的链接? href
属性迭代应仅针对rel='test'
的链接,对吗?
HTML:
<a href="test2" rel="test">Proper Test</a> // I want to grab this one
<a href="testing" rel="testing">Test</a>
<a href="testing" rel="testing">Test</a>
<a href="test2" rel="besting">Test</a>
<a href="testing" rel="test">Test</a>
答案 0 :(得分:0)
修正了一些js错误并对html做了假设。只需使用console.log,alert或控制台调试器逐步进行故障排除,您就可以捕获这些内容。
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
if (links[i].getAttribute('rel') == 'test') {
if (links[i].getAttribute('href') == 'test2') {
console.log("link index:" + i );
}
}
}
&#13;
<a href="test2" rel="test">Test</a>
<a href="best" rel="testing">Test</a>
<a href="thetest2" rel="testing">Test</a>
<a href="test2" rel="besting">Test</a>
<a href="thetest2" rel="testing">Test</a>
&#13;
答案 1 :(得分:0)
通过查看您的评论,我认为您已经陷入了javascript关闭。通过这个循环很简单,你只需要在满足条件的地方打破。
var links = document.getElementsByTagName('link');
var mylink = '';
for (var i = 0; i < links.length; i++)
{
if (links[i].getAttribute('rel').indexOf('test') !== -1)
{
if (links[i].getAttribute('href').indexOf('test2') !== -1)
{
mylink = links[i];
break; //If you need the first one. else create an array and keep pushing the ietms.
}
}
}
console.log(mylink);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="test" href="www.test2.com">
<link rel="test1" href="www.test2.com">
<link rel="test2" href="www.test2.com">
<link rel="test3" href="www.test2.com">