简体   繁体   English

添加新的父div,然后在此父div中添加下一个div

[英]Add new parent div and next a div inside this parent div

I want to do a simple manipulation but i don't understand why it's don't work i have a div : 我想做一个简单的操作,但是我不明白为什么它不起作用我有一个div:

<input type='button' value='validate' class='popupjq'>

And i want to add a parent div to this input and also a 'brother' div for have this result : 我想向此输入添加一个父div,并为此添加一个“兄弟” div:

<div id = 'id_parent'>
   <input type='button' value='validate' class='popupjq'>
   <div id = 'id_brother'></div>
</div>

So i use this javascript : 所以我用这个javascript:

$(".popupjq").each(function() {
    var divParent = $("<div id = 'id_parent' style='display:inline-block; position:relative;'>");
    var divCache = $("<div id='toto'>");
    $(this).wrap(divParent);
    $(divParent).append(divCache);
});//bracket missing

My problem is that the parent div is create but not the brother div. 我的问题是父div是create而不是brother div。

You can use insertAfter() to put the second element where you require: 您可以使用insertAfter()将第二个元素放在所需的位置:

$(".popupjq").each(function() {
    $(this).wrap('<div id="id_parent" style="display: inline-block; position: relative;"></div>');
    $('<div id="toto"></div>').insertAfter(this);
});

Example fiddle 小提琴的例子

  • You haven't closed your each-loop properly (check brackets). 您尚未正确关闭每个循环(选中方括号)。
  • You should specify the DIVs' HTML as strings. 您应该将DIV的HTML指定为字符串。
  • Using "each" implies you're planning to apply this method on several elements. 使用“每个”意味着您打算将此方法应用于多个元素。 In this case you should work with classes instead of IDs in your DIVs' HTML, since IDs are meant to exist exactly one time in the DOM. 在这种情况下,您应该使用类而不是DIV的HTML中的ID,因为ID应该在DOM中恰好存在一次。
  • You haven't addressed your parent DIV properly (see my approach). 您没有正确处理父级DIV(请参阅我的方法)。

http://jsfiddle.net/1yn8qgg3 (CSS with background colors to visually mark the DIVs) http://jsfiddle.net/1yn8qgg3 (带有背景颜色的CSS,用于在视觉上标记DIV)

$(".popupjq").each(function() {
  var divParent = "<div class='class_parent'></div>";
  var divCache = "<div class='class_toto'></div>";
  $(this).wrap(divParent);
  $(this).parent().append(divCache);
});

Hope this helps. 希望这可以帮助。

Do the following, to get the result 执行以下操作以获得结果

$(function(){
$(".popupjq").each(function() {
    var divParent = $("<div id = 'id_parent' style='display:inline-block; position:relative;'> </div>");
    var divCache = $("<div id='toto'> </div>");
    $(this).wrap(divParent);
    $(this).append(divCache);
});

});

Fiddle 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM