2014-02-27 28 views
1
<div class="container-fluid"> 
<img class="pull-left" onclick="MarkPopup()" style="width:50px;height:50px" src="/assets/mark.jpg"> 
<ul class="nav pull-right"> 
<li> 
<li> 
<a href="/ContactClub">Contact Club</a> 
</li> 
<li> 
<li class="dropdown"> 
</ul> 
</div> 

我想将href值“/ ContactClub”更改为“somethingelse”。这样做怎么样?如何使用javascript或jquery更改href值?

回答

2

两种方式;)

jQuery的风格:

// Select a with href attribute = /ContactClub 
$('a[href="/ContactClub"]').prop('href', 'newhref...'); 

纯JS的解决方案(未经测试)

var elements = document.getElementsByTagName('a'); 
for (var i = 0; i < elements.length; i++) { 
if (element[i].href === '/ContactClub') { 
    if (element.setAttribute !== 'function') { 
    element[i].href = 'newhref'; 
    } else { 
    element[i].setAttribute('href', 'newhref'); 
    } 
} 
} 
+0

'setAttribute'不应该优先。实际上,在这种情况下根本不应该使用它。如果存在,请直接设置属性。 – bearfriend

0

尝试

$("li a").attr("href","new value"); 
1

您可以使用prop()attr()

$('a[href="/ContactClub"]').attr('href', 'New Href here'); 

或:

$('a[href="/ContactClub"]').prop('href', 'New Href here'); 

Fiddle Demo

1

我想补充一个ida标签:

<a id="contact_link" href="/ContactClub">Contact Club</a> 

然后做要么,

$('#contact_link').attr('href', 'new url'); 

,或者

document.getElementById('contact_link').href = 'new url'; 

注意:您还可以使用jQuery的prop方法以同样的方式如上attr。这有点偏好。由于href主要被认为是一个属性(与相应的,但不是动态的或断开的js属性),我会建议使用attr。其他属性如value将取决于您尝试检索的内容。对差异进行一些研究。