为页面上使用的每个实例更改jquery变量

时间:2013-02-05 19:24:02

标签: javascript jquery

我正在设置一个包含指向不同文档的多个链接的页面。由于链接的名称与它们链接的文档相匹配,我想我会编写一个脚本,该脚本将带有下划线的内部html,并在其周围生成链接标记,并在链接中输入每个特定的链接名称。

我编写的脚本运行正常,但它只运行一次并更新所有链接,每个链接都有一个相同的链接。有没有办法可以让每个实例单独更改它们?

对不起,如果我已经诅咒了我的解释!

这是我目前的代码:

<u>Link1</u>
<u>Link2</u>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

<script>
innerU = $("u").html();
$("u").html("<a href=mywebsite.com/" + innerU + ".pdf>" + innerU + "</a>");
</script>

4 个答案:

答案 0 :(得分:4)

您可以使用jQuery的each()将您想要的转换应用于您网页中的每个<u>元素。像这样:

$("u").each(function() {
    var innerU = $(this).html();
    $(this).html("<a href='mywebsite.com/" + innerU + ".pdf'>" + innerU + "</a>");
});

编辑:在href值周围添加引号以生成有效的HTML。感谢Kolink注意。

答案 1 :(得分:3)

请改为尝试:

(function() { // create a closure to avoid leaking variables
   var tags = document.getElementsByTagName("u"), l = tags.length, i, t, a;
   for( i=0; i<l; i++) {
      a = document.createElement('a');
      a.href = "http://mywebsite.com/"+tags[i].firstChild.nodeValue+".pdf";
      a.appendChild(tags[i].firstChild);
      tags[i].appendChild(a);
   }
})();

这样做有几个原因:

  1. 它是vanilla JavaScript,因此运行速度快了数百倍
  2. 它使用闭包以避免变量污染全局范围
  3. 它使用DOM方法而不是innerHTML(这是jQuery的.html()使用的方法)
  4. 它将文本节点视为文本,如果您在其中包含&eacute;等HTML实体,这一点非常重要。

答案 2 :(得分:1)

这应该可以解决问题。

$("u").each(function () {

    var innerU = $(this).html();
    $(this).html("<a href=mywebsite.com/" + innerU + ".pdf>" + innerU + "</a>");

});

尽管您的代码存在很多“错误”。例如,使用<u>标记生成链接?为什么不直接使用anhors并动态设置它们的href属性,如下所示:

<a href="#" class='coollink'>Link1</a>
<a href="#" class='coollink'>Link2</a>

<script>
$("a.coollink").each(function () {
    $(this).attr("href", "//mywebsite.com/" + $(this).html() + ".pdf");
});
</script>

答案 3 :(得分:-2)

您可以使用JQuery的.each()方法。

$('u').each(function(){
    innerU = $(this).html();
    $(this).html("<a href=mywebsite.com/" + innerU + ".pdf>" + innerU + "</a>");
});

<强> Example