我有以下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的方法,因为它们具有相同的类名。< / p>
例如,我想将第一个div的标签中的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>
对此有任何帮助将不胜感激..
答案 0 :(得分:3)
浏览每个图块并更改其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语句(因此它会更快)。
答案 1 :(得分:2)
你可以试试这个
$('div.tile').each(function(){
var a = $(this).find('a:first');
a.attr('href', a.attr('href') +'/'+ $(this).find('.tileCaption h4').text());
});
更新:经过与OP
的长时间聊天后,我得到了要求,这就是解决方案:
var urls = {
'Logos':'http://www.google.com/',
'Adverts':'http://www.yahoo.com/'
};
$('div.tile').each(function(){
var a = $(this).find('a:first');
a.attr('href', urls[$(this).find('.tileCaption h4').text()]);
});
答案 2 :(得分:1)
首先关闭:类属性的正确选择器语法是.className
,而不是#className
(#className
会搜索 id 的节点是“className” “)。
然后:你应该遍历你的节点,并在每个节点上重复调用一个函数。使用.each()
功能:
$('.tile').each(function(){
//when this function executes, 'this' points to the current node
// $(this).find(...) will look only through the descendants of 'this'
var h4 = $(this).find('h4').html();
$(this).find('a').attr('href', "http://test-site.local/"+h4 );
});
答案 3 :(得分:0)
$('.tile').each(function () {
$('> a', this).attr('href', function(){
return this.href + $(this).find('h4').text();
});
});