JQuery循环,它提取元素的特定属性并将其添加到href

时间:2011-10-04 02:16:13

标签: jquery loops jquery-selectors

所以我整天都在工作,搜索和捶打我的头。我对所有这些都有所不同,所以如果我的编码非常适合我,我很抱歉。我想要做的是创建一个机制来记住当前页面的锚点网址,但是当用户改变国家时,改变国家页面中的链接以使用户回到他们所在的位置但在新国家名录。

到目前为止,我已经让选择器从上一页拉出信息并将其保存为熟食。我甚至按照自己的意愿改变了网址。问题是我给每个标签一个国家代码作为名称。当代码执行时,我无法获取它来拉动每个名称并将其应用于bespoke的href,因为它在页面中移动。我只能得到第一个选择,或者最后一个选择它适用于所有这些。任何关于我做错的见解都会很棒。

$('#setNation').click(function(event) {
   var fromPage = window.location.pathname
   $.cookie("pageFrom", fromPage);  
});

$('.nationSelect').each(function() {
   $('.nationSelect').attr("herf", "http://domain.com/"+$(this).attr("name")+$.cookie("pageFrom"));
});

HTMl看起来像这样

<div id="nationList">
  <a name="de" class="nationSelect">
    <div id="nationListIcon">
      <div id="nationListImg" style="background-position: -229px -76px;"></div>
      <p lang="de" xml:lang="de">Deutschland</p>
    </div>
  </a>
  <a name="es" class="nationSelect">
    <div id="nationListIcon">
      <div id="nationListImg" style="background-position: -305px -76px;"></div>
      <p lang="es" xml:lang="es">España</p>
    </div>
  </a>
  <a name="fr" class="nationSelect">
    <div id="nationListIcon">
      <div id="nationListImg" style="background-position: -380px -76px;"></div>
      <p lang="fr" xml:lang="fr">France</p>
    </div>
  </a>
</div>

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

你有一个错字。它的href,而不是herf。赫兹听起来像是从一个肮脏的女孩身上捡到的东西。

//Your current code changes the href for all links of class nationSelect. This means whatever the last link changed is will be applied to all links on the page
$('.nationSelect').attr("herf", 

//What you want is for only the current one to get the new value. So use $(this)
$('.nationSelect').each(function() {
    $(this).attr('href', 'http://domain.com/' + $(this).attr('name') + '/morestuff');
});