代码之家  ›  专栏  ›  技术社区  ›  Jamie Taylor

jQuery试图动态插入另一个div的HTML吗?

  •  3
  • Jamie Taylor  · 技术社区  · 15 年前

    这真的很难解释。我在一张桌子里有几个有身份证的人

    <table id="dgAvailable">
      <tr> <td> <div id="HEYD"> </td> </tr> <tr> <td> <div id="HANW"> </td> </tr> 
    </table>
    

    我需要用这些内容填充这些分区

    <div class="evenprop"><h3>Hanworth</h3><span class="locid" style="display:none">HANW</span></div>
    <div class="evenprop"><h3>Heydon</h3><span class="locid" style="display:none">HEYD</span></div>
    

    所以我需要得到一个div,它包含与我的另一个div具有相同id的locid,然后在表dgavable中的div中插入html

    $('#dgAvailable > tr > td > div').each(function(){
      if $(this).attr('id') = $('.evenprop > .locid').attr('id') {
      $(this).html() = $('.evenprop > .locid').parent().html()
    });
    

    我真的没有别的方法来描述这个?

    杰米

    2 回复  |  直到 15 年前
        1
  •  2
  •   Nick Craver    15 年前

    试试这个:

    $("div.evenprop .locid").each(function() {
       $("#" + this.innerHTML).html($(this).parent().clone());
    });
    

    You can try out a demo against your markup here .


    如果可以控制其他标记,则可以使用数据属性对其进行大量清理,如下所示:

    <div class="evenprop" data-locid="HANW"><h3>Hanworth</h3></div>
    <div class="evenprop" data-locid="HEYD"><h3>Heydon</h3></div>
    

    然后jQuery也变得简单了一些,如下所示:

    $("div.evenprop").each(function() {
       $("#" + $(this).attr('data-locid')).html($(this).clone());
    });
    

    或者,如果不需要旧节点,只想移动它,请使用 .append()

    $("div.evenprop").each(function() {
       $("#" + $(this).attr('data-locid')).append(this);
    });
    
        2
  •  4
  •   BGerrissen    15 年前

    我应该这么做。

    $('.locid').each(function(){
       $('#'+$.trim($(this).text())).html(this.parentNode.cloneNode(true));
    });