2014-02-27 90 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將取決於您嘗試檢索的內容。對差異進行一些研究。