[英]Manipulate the href attribute using jQuery
I have a few URLs and would like to add a slash (/) before them. 我有一些URL,并想在它们之前添加一个斜杠(/)。
This is how they look in my HTML: 这就是它们在我的HTML中的外观:
<li class="link">
<a href="products/">Products</a>
</li>
<li class="link">
<a href="team/">Team</a>
</li>
<li class="link">
<a href="contact/">Contact</a>
</li>
How can I manipulate the link in the href
attribute, so it looks eg like this: /products/
? 我该如何操作href
属性中的链接,使其看起来像这样: /products/
?
The solution must work on IE 10! 该解决方案必须适用于IE 10!
You can use jQuery attr()
method to do it like following. 您可以使用jQuery attr()
方法执行以下操作。
$('.link a').attr('href', function(){ return '/' + $(this).attr('href'); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li class="link"> <a href="products/">Products</a> </li> <li class="link"> <a href="team/">Team</a> </li> <li class="link"> <a href="contact/">Contact</a> </li> </ul>
You can use attr()
to change links 您可以使用attr()
更改链接
$('li.link a').each(function() { $(this).attr('href', '/' + $(this).attr('href')); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <li class="link"> <a href="products/">Products</a> </li> <li class="link"> <a href="team/">Team</a> </li> <li class="link"> <a href="contact/">Contact</a> </li>
您可以使用$(element).attr("href", "http://example.com")
更改URL。
Could be something like this 可能是这样的
var name = "/" + $('.link').children().attr('href');
$('.link').children().attr('href',name);
Checkout the jquery .attr() documentation http://api.jquery.com/attr/ 检出jquery .attr()文档http://api.jquery.com/attr/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.