如何使用jQuery或JavaScript重复div?

时间:2013-04-15 23:40:44

标签: javascript jquery json jquery-mobile

我有一个带有以下div标签的HTML页面

<div data-role="page" id="pageHome" data-theme="a">
  <div data-role="content">
    <center>
      <h3><a href="#pageHome" data-role="none"><img src="images/logo.png" /></a></h3>
    </center>
    <div class="dydivarr0"> </div>
    <br />
    <div data-role="controlgroup" class="ui-btn-right"> <a href="#page1" data-role="button">Next</a> </div>
  </div>
</div>



<div data-role="page" id="page1" data-theme="a">
  <div data-role="content">
    <center>
      <h3><a href="#pageHome" data-role="none"><img src="images/logo.png" /></a></h3>
    </center>
    <div class="dydivarr1"> </div>
    <br />
    <div data-role="controlgroup" class="ui-btn-right"> <a href="#page2" data-role="button">Next</a> </div>
  </div>
</div>

<div data-role="page" id="page2" data-theme="a">
  <div data-role="content">
    <center>
      <h3><a href="#pageHome" data-role="none"><img src="images/logo.png" /></a></h3>
    </center>
    <div class="dydivarr2"> </div>
    <br />
    <div data-role="controlgroup" class="ui-btn-right"> <a href="#page3" data-role="button">Next</a> </div>
  </div>    

dydivarr是使用JSON从Web动态生成的响应。使用该响应我创建动态div内容,接下来我想重复该div,如上所示。有没有比重复静态HTML代码更好的方法?我想必须有很少的jQuery或JavaScript技巧。

任何帮助都会被暗示。

4 个答案:

答案 0 :(得分:4)

所以你想要你的div的cloneNode,所以尝试这样的事情

var div = document.getElementById('myDiv'),
clone = div.cloneNode(true);
clone.id = "some_id";
document.body.appendChild(clone);

答案 1 :(得分:1)

这样的东西?  Sample Fiddle

var lastSection = $('[data-role="page"]:last'); //get the last page probably you can use this to increment the id based on last id
var newSection = lastSection.clone(false);//default is false anyways, if you want to carry over data and events you can use true.
newSection.attr('id','setthenewid');//set the new id
$('div[class^=dydivarr]',newSection).attr('class','newclass'); //set the new class for your divarr
$('.ui-btn-right a',newSection).attr('href','newurlmap');//set the new url map 
lastSection.after(newSection); //place the entire page section in the end

答案 2 :(得分:1)

更新:

简单代码有效。这只是我错误的做法

<script type="text/javascript">

for(var lp=0; lp < 10; lp++)
{
document.write('<div data-role="page" id="page'+lp+'" data-theme="a">');
document.write('  <div data-role="content">');
document.write('    <center>');
document.write('      <h3><a href="#page0" data-role="none"><img src="images/logo.png" /></a></h3>');
document.write('     </center>');
document.write('     <div class="dydivarr+lp+'"> </div>');
document.write('     <br /> ');
document.write('     <div data-role="controlgroup" class="ui-btn-left"> <a href="#page'+(lp-1)+'"     data-role="button">Previous</a> </div>');
document.write('     <div data-role="controlgroup" class="ui-btn-right"> <a href="#page'+(lp+1)+'" data-role="button">Next</a> </div>');
document.write('   </div>');
document.write(' </div>');

}

</script>

由于

答案 3 :(得分:0)