对于href等于myValue的每个链接

时间:2012-09-17 09:54:02

标签: jquery html

为什么以下内容没有将文字更改为有效?

//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但是我可能会把它弄错了有人可以确保我已经正确完成了上述工作吗?

6 个答案:

答案 0 :(得分: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/

答案 1 :(得分:6)

将其写为:

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

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

答案 2 :(得分:5)

试一试:

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

答案 3 :(得分:5)

修正:

//JAVASCRIPT/JQUERY:

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

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

答案 4 :(得分: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

答案 5 :(得分:0)

利用the array functions available to you in JS

这里是the most minimal solution I could come up with

$('a')
.filter('a[href*="mywebsite.co.uk"]')
.text('It worked!');
相关问题