获取特定元素中的锚点href属性和文本值的列表

时间:2014-10-02 23:22:50

标签: javascript loops hyperlink extract

<li class="bottom">
  <a role="menuitem" aria-haspopups="true" href="/myshop.php">Your Shops</a> &raquo;
  <ul role="menu" class="menu-dropdown" id="menu-sub-shops">
    <li><a href="/myshop.php?shopid=300101">A</a> (<a href="/myshop.php?shopid=300101&act=quickstock">qs</a>)</li>
    <li><a href="/myshop.php?shopid=300739">B</a> (<a href="/myshop.php?shopid=300739&act=quickstock">qs</a>)</li>
    <li><a href="/myshop.php?shopid=300078">C</a> (<a href="/myshop.php?shopid=300078&act=quickstock">qs</a>)</li>
    <li><a href="/myshop.php?shopid=300591">D</a> (<a href="/myshop.php?shopid=300591&act=quickstock">qs</a>)</li>
    <li><a href="/myshop.php?shopid=306981">E</a> (<a href="/myshop.php?shopid=306981&act=quickstock">qs</a>)</li>
    <li class="bottom"><a href="/myshop.php?shopid=300232">F</a> (<a href="/myshop.php?shopid=300232&act=quickstock">qs</a>)</li>
  </ul>
</li>
var t1 = document.getElementById("menu-sub-shops");
for (var i = 0; i < t1.length; i++) {
  var t2 = t1[i].getElementsByTagName('li');
  for (var j = 0; j < t2.length; j++) {
    var t3 = t2[j].getElementsByTagName('a');
    for (var k = 0; k < t3.length; k++) {
      eval("var shopid" + k + " = " + t3[k].attributes['href'].value);
      console.log(t3[k].attributes['href'].value);
    }
  }
}

我试图获取与相关名称的链接无济于事。 输出我想要得到:

  

A - /myshop.php?shopid=300101
  B - /myshop.php?shopid=300739
  C - /myshop.php?shopid=300078
  D - /myshop.php?shopid=300591
  E - /myshop.php?shopid=306981

My JSFiddle

1 个答案:

答案 0 :(得分:0)

您可以使用querySelectorquerySelectorAll

如果您在链接中添加一个类,则可以轻松区分一个类。

<ul role="menu" class="menu-dropdown" id="menu-sub-shops">
    <li><a href="/myshop.php?shopid=300101" class="pickme">A</a> (<a href="/myshop.php?shopid=300101&act=quickstock">qs</a>)</li>
    <li><a href="/myshop.php?shopid=300739" class="pickme">B</a> (<a href="/myshop.php?shopid=300739&act=quickstock">qs</a>)</li>
</ul>

现在您的代码变为

var links = document.querySelectorAll("#menu-sub-shops a.pickme");
for (var i = 0; i < links.length; i++) {
    var text = links[i].text;
    var href = links[i].href;
}