【问题标题】:jQuery - putting a closing div after the current this element?jQuery - 在当前这个元素之后放置一个关闭 div?
【发布时间】:2010-08-12 00:30:32
【问题描述】:

我正在尝试使用 div 标签动态分割每个生成标签和硬编码输入对。我似乎能够让 div 包围标签(参见下面的源代码),但我希望 div 也能包围输入。

这只有 div 围绕输入:

​ $(文档).ready(函数(){ $("#sg1 输入").each(function(){ $("​
" ) .insertBefore(这个); }); }); ​脚本> ​

http://jsfiddle.net/RM5wG/12/

我想弄清楚如何让 jQuery 将 div 附加到整个标签对,而不是在标签周围放置 div,即最终的前景如下:

​...​标签> ​ ​

【问题讨论】:

    标签: jquery


    【解决方案1】:

    您可以像这样使用.wrapAll() 来做到这一点:

    $(function(){
      $("#sg1 input").each(function(){
        $(this).wrap('<div></div>').parent()
               .prepend('<label for="'+ this.name +'">'+$(this).val()+'</label>');
      });
    });
    

    You can check it out here。或者,更接近您的原作:

    $(function(){
        $("#sg1 input").each(function(){
        $(this).before('<label for="'+ this.name +'">' + $(this).val() + '</label>')
               .prev().andSelf().wrapAll('<div></div>');
        });
    });
    

    You can give it a try here,我们正在做的是在输入之前添加标签,然后使用.prev().andSelf() 将其添加到集合中,然后我们只是在两者上调用.wrapAll()元素。

    【讨论】:

      【解决方案2】:
      $("input #sg1").each(function(){
          $(this).wrap("<div></div>");
          $("​​<label for=\""+$(this).attr("name")+"\">"+$(this).val()+"​</label>").insertBefore(this);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-01
        相关资源
        最近更新 更多