我有以下HTML。我想实现jQuery来为每个readmore链接添加href属性。我想知道如何在这里选择readmore链接。 readmore链接是动态生成的,我想为每个readmore链接提供不同的值。有什么办法吗?我试过用这个。
更新
我想在.content的第一个孩子里面找到一个标签......怎么弄它...... ???
jQuery('.content.c7:nth-child(1)').attr('href','www.google.com');
但它没有用。我在这做错了什么?请帮帮我。
<div class="content c7">
<div class="products">
<div id="post_content">
Hai
</div>
<div class="end readmore">
<a >Read More</a>
</div>
</div>
<div class="products">
<div id="post_content">
hello
</div>
<div class="end readmore">
<a>Read More</a>
</div>
</div>
<div class="products">
<div id="post_content">
how are you
</div>
<a >Read More</a>
</div>
<div class="products">
<div id="post_content">
I am fine
</div>
<div class="end readmore">
<a>Read More</a>
</div>
</div>
</div>
答案 0 :(得分:1)
你可以这样做:
$('.content.c7 .readmore a').attr('href','www.google.com');
<强>更新强>
$('.content.c7 .readmore a').each(function (index) {
if (index == 0) {
// Set href for the first element
$(this).attr('href', 'www.google.com');
} else if (index == 1) {
// Set href for the second element
$(this).attr('href', 'www.yourlink.com');
}
// Similarly set href for other elements individually
});
<强>更新强>
$('.content.c7 .readmore:eq(0) a').attr('href','www.google.com');
答案 1 :(得分:0)
对于所有“阅读更多”链接,您可以选择以下内容:
var rmlinks = jQuery('.content.c7 .readmore a');
如果你想将它们全部设置为相同的东西,你可以通过以下方式完成:
rmlinks.attr('href', 'http://example.com');
如果你想根据你在其他地方的hrefs列表逐个点击它们,那么:
for ( i = 0; i < rmlinks.length; ++i )
{
var newhref = "???"; // up to you
$(rmlinks[i]).attr('href', newhref);
}
答案 2 :(得分:0)
新代码工作演示http://jsfiddle.net/cse_tushar/vZnUU/2/
$(document).ready(function () {
var links = ["www.google.com", "www.yahoo.com", "www.fb.com","www.hotmail.com"];
i =0;
$('.products a').each(function () {
$(this).attr('href', links[i]);
i++;
});
});
工作演示http://jsfiddle.net/cse_tushar/vZnUU/
$(document).ready(function () {
$('.products div a').each(function () {
$(this).attr('href','www.google.com');
});
});
如果您只想在文本为“阅读更多”
时更改链接工作演示http://jsfiddle.net/cse_tushar/vZnUU/1
$(document).ready(function () {
$('.products div a').each(function () {
if($(this).text() == 'Read More')
$(this).attr('href','www.google.com');
});
});
答案 3 :(得分:0)
假设以下结构
<div class="content c7">
<div id="product_1" class="products">
<div id="post_content">
Hai
</div>
<div class="end readmore">
<a >Read More</a>
</div>
</div>
...
</div>
我认为这就是你想要的:
$('.content.c7 .products').each(function() {
var the_id = $(this).attr('id');
$(this).find('.readmore > a').attr('href', 'www.google.com/' + the_id);
});
注意:您不应多次使用相同的ID(例如post_content
)