[英]How to change href value using javascript or jquery?
<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>
I want to change the href value "/ContactClub" to "somethingelse". 我想将href值“ / ContactClub”更改为“ somethingelse”。 How is this done please?
请问这是怎么做的?
Two ways ;) 两种方式;)
jQuery style: jQuery样式:
// Select a with href attribute = /ContactClub
$('a[href="/ContactClub"]').prop('href', 'newhref...');
Pure-js solution (untested) Pure-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');
}
}
}
I would add an id
to the a
tag: 我会添加一个
id
到a
标签:
<a id="contact_link" href="/ContactClub">Contact Club</a>
And then do either, 然后要么
$('#contact_link').attr('href', 'new url');
or, 要么,
document.getElementById('contact_link').href = 'new url';
Note: You can also use the jQuery prop
method in the same fashion as attr
above. 注意:您也可以按照与上述
attr
相同的方式使用jQuery prop
方法。 This is somewhat a matter of preference. 这有点偏爱。 As
href
is principally thought of as an attribute (with a corresponding, but not dynamic or disconnected js property), I would suggest using attr
. 由于
href
原则上被认为是一个属性(具有相应的js属性,但没有动态或断开连接的js属性),因此建议您使用attr
。 Other attributes like value
will depend on what you're trying to retrieve. 其他属性(例如
value
将取决于您要检索的内容。 Do a bit of research on the differences. 对差异进行一些研究。
尝试
$("li a").attr("href","new value");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.