I have a document structure that looks similar to this:
<article id="post1" class="post-5 page type-page" >
<section class = "holder clearfix">
<div class = "four columns">
<a title class = "single-image short-link" href "http://whatever.com" target = "self">
</a>
</div>
<div class = "four columns">
<a title class = "single-image short-link" href "http://whatever.com" target = "self">
</a>
</div>
<div class = "four columns">
<a title class = "single-image short-link" href "http://whatever.com" target = "self">
</a>
</div>
<div class = "four columns">
<a title class = "single-image short-link" href "http://whatever.com" target = "self">
</a>
</div>
</section>
</article>我想要做的是向每个添加一个带有类和唯一ID的div,一个使用JQuery的元素。
最终的结果会是这样的
<article id="post1" class="post-5 page type-page" >
<section class = "holder clearfix">
<div class = "four columns">
<a title class = "single-image short-link" href "http://whatever.com" target = "self">
<div id="button1" class = "shiny-button"> </div> // unique ID
</a>
</div>
<div class = "four columns">
<a title class = "single-image short-link" href "http://whatever.com" target = "self">
<div id="button2" class = "shiny-button"> </div> // unique ID
</a>
</div>
<div class = "four columns">
<a title class = "single-image short-link" href "http://whatever.com" target = "self">
<div id="button3" class = "shiny-button"> </div> // unique ID
</a>
</div>
<div class = "four columns">
<a title class = "single-image short-link" href "http://whatever.com" target = "self">
<div id="button4" class = "shiny-button"> </div> // unique ID
</a>
</div>
</section>
</article>到目前为止,下面的JQuery代码将我带到一半的地方:
$('<div/>', {
class:'shiny-button',
}).appendTo('.single-image');我尝试使用类似于下面的代码,但我似乎无法正确地理解它
$('<div/>', {
class:'shiny-button',
id: 'button1',
}).appendTo('.holder .four:nth-child(1)');谢谢。
发布于 2014-01-23 23:57:07
试着用每一种。所以
$('.single-image').each(function(index){
//Append new element to $(this)
//index will be a counter
//$(this) = the current $('.single-image') element
});我相信你可以用这个索引来成为唯一的。我不记得了,但是.each()函数是在jQuery中记录的。
发布于 2014-01-24 00:11:57
试一试
$('#post1 .single-image').append(function(i){
return '<div id="button'+(i+1)+'" class = "shiny-button"> dd</div>'
})演示:小提琴
https://stackoverflow.com/questions/21321769
复制相似问题