我试图在另一个 div 中添加一个 div,这两个 div 都是动态创建的。老实说,我不确定为什么不将它添加到 newDiv
(function ($){
$.fn.dropdown = function(){
return this.each(function(){
//Gather information
var id = $(this).attr("id");
//Get the original selection and keep it as a reference
var original = $(this);
//Create a new div with a predefined class and taking the ID from the original HTML.
var newDiv = $("<div id='"+id+"' class='dropDownJs' />");
//Remove the id from the original HTML
original.removeAttr("id");
//Encapsulate the original dropdown with a new parent div
original.wrap(newDiv);
//Create children divs within the parent div for each option within the selection HTML.
original.children().each(function(){
//Grab crucial values from the original.
//The value of the option
var val = $(this).val();
//The text from the option (label)
var text = $(this).text();
//Child divs to create
var child = $("<div class='dropDownJsChild'></div>");
newDiv.append(child);
});
});
}
}(jQuery))
为了所有密集的目的,这个 jQuery 正在操纵这个 HTML 片段
<select id="test" class="dropdown">
<option value="something1">Something 1</option>
<option value="something2">Something 2</option>
<option value="something3">Something 3</option>
</select>
进一步澄清:
<script>
$(document).ready(function(){
$(".dropdown").dropdown();
});
</script>
不幸的是,newDiv.add(child)
不工作,我也试过 newDiv.append(child)
也失败了。
最佳答案
编辑:事实证明,OP 试图创建无效的 HTML 结构,将选项标签包装在 div 标签或其他任何内容中,所以让我们关闭它
不要创建一个与现有 div 具有相同 id 的 div,并像这里一样包装它们:original.wrap(newDiv);
删除之前的 id
其次,您使用的不是您要查找的 add 函数,而是使用 append:
newDiv.append(child);
add 函数扩展了子对象的 jquery 对象 newDiv。 append 将元素移动到 DOM 中的其他元素。
关于javascript - 在另一个先前动态创建的 div 中附加一个动态 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25160447/