我有以下 HTML
<div class='tile'>
<a href='http://test-site.local' >
<div class='tileContents'>
<div class='tileImage'>
<i class='icon-'></i>
</div>
<div class='tileCaption'>
<h4>Logos</h4>
<p></p>
</div>
</div>
</a>
</div>
<div class='tile'>
<a href='http://test-site.local' >
<div class='tileContents'>
<div class='tileImage'>
<i class='icon-'></i>
</div>
<div class='tileCaption'>
<h4>Adverts</h4>
<p></p>
</div>
</div>
</a>
</div>
我想将 href
属性更新为我希望使用 h4
标记的值作为目标和区分两个 DIV 的任何 URL相同的类名。
例如,我想将第一个 div 的 a 标记中的 URL 更新为:
<a href="http://www.google.com">
so if the value of the h4 tag = "Logos" then update the URL to "http://www.google.com"
第二个 DIV 也是如此:
<a href="http://www.yahoo.com">
so if the value of the h4 tag = "Adverts" then update the URL to "http://www.yahoo.com"
我有以下内容,但我认为我没有正确获取选择器:
<script src="/script/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var value = $('div.tile h4').html();
if (value = "Logos");
$("DIV.tile a").attr("href", "http://www.google.com");
if (value = "Adverts");
$("DIV.tile a").attr("href", "http://www.yahoo.com");
});
</script>
如有任何帮助,我们将不胜感激..
最佳答案
遍历每个图 block 并更改其 children('a')
的 href
$('.tile').each(function(){
$(this).children('a').attr("href", "http://test-site.local/"+$(this).find('h4').text());
});
.find()
和 .children()
的区别在于 .find()
在元素内部找到你想要的东西,而.children()
仅沿着 DOM 树向下移动一个级别(因此速度更快)。
使用 .text()
获取单词并将其简单地放在 url 后面而不是使用 if 语句(这样会更快)。
关于javascript - 用 Jquery 替换 URL 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19275926/