2012-09-17 18 views
7

为什么下面的内容没有改变文本到它的工作?对于href等于myValue的每个链接

//JAVASCRIPT/JQUERY: 

$('a').each(function(i) { 
    if($(i).attr("href") == "mywebsite.co.uk") 
    { 
     $(i).innerHTML = "It Worked!"; 
    } 
}); 


//HTML: 

<a href="mywebsite.co.uk"></a> 

调试它似乎并没有拿起HREF value.attr但我可以得到它都是错误可以有人请确保我有上面做得正确?

回答

11

i是元素的索引,你想要的元素,应该用应该使用类似:

// The first argument is the index, the second is the element 
$('a').each(function(index, element) { 
    if($(element).attr("href") == "mywebsite.co.uk") 
    { 
     $(element).html("It Worked!"); // Change this to .html() 
    } 
    console.log('Index is:'+index+', Element is'+element); 
});​ 

<a href="mywebsite.co.uk"></a> 

而且,我改变了.innerHtml().html("content in here")。更新返回的<a></a>标签(element)中的HTML。

检查此JSFiddlehttp://jsfiddle.net/2scug/1/

+0

接受你的元素和索引参数给我解释。 – Anicho

4

试试:

$('a').each(function(i,v) { 
    console.log(); 
    if($(v).attr("href") == "mywebsite.co.uk") 
    { 
     $(v).html('It worked!'); 
    } 
}); 
+0

感谢您显示元素参数,但@JustAnil的答案解释了什么“v”如此接受他/她作为解决我的问题的答案。 – Anicho

+1

@Anicho好的,很高兴在某种方式有用;-) –

5

它可能更短把它写为:

$('a[href="mywebsite.co.uk"]').each(function() { 
    $(this).html("It Worked!"); 
}); 

还有一个原因是jQuery有HTML()函数。它清理所有可能的内存泄漏,然后使用innerHTML的内部设置你需要;-)

5

值修正:

//JAVASCRIPT/JQUERY: 

$('a').each(function(i) { 
    if($(this).attr("href") == "mywebsite.co.uk") 
    { 
     $(this).html("It Worked!"); 
    } 
}); 

的jsfiddle: http://jsfiddle.net/kAWdy/

1

在这里,我已经做了完整的箱以上问题。您可以点击这里演示链接

演示http://codebins.com/bin/4ldqp75/1/For%20each%20link%20where%20href%20equal

<a href="mywebsite.com"> 
</a> 
<a href="mywebsite.co.uk"> 
</a> 
<a href="mywebsite.us"> 
</a> 
<a href="mywebsite.in"> 
</a> 
<input type="button" id="btn1" value="Get Text"/> 

的jQuery:

$(function() { 

    $("#btn1").click(function() { 
     $("a").each(function() { 
      if ($(this).attr('href').trim() == "mywebsite.co.uk") { 
       $(this).html("UK Website Link"); 
      } else { 
       $(this).html("Website Link"); 
      } 

     }); 
    }); 

}); 

CSS

a{ 
    display:block; 
} 
input[type=button]{ 
    margin-top:10px; 
} 

演示http://codebins.com/bin/4ldqp75/1/For%20each%20link%20where%20href%20equal