简体   繁体   English

为什么这个appendTo不起作用?

[英]Why isn't this appendTo working?

JS: JS:

 var $sel = $("<select></select>");
 $sel.append("<option>1</option");
 var $sel = $sel.appendTo("<div></div>");
 $sel.insertAfter("#mydiv");

HTML: HTML:

 <div id=mydiv></div>

This only appends the select box, but not wrapped in the div. 这仅附加选择框,而不包装在div中。 I would like the select wrapped by another div appended to #mydiv. 我想要由附加到#mydiv的另一个div包装的选择。 I tried: 我试过了:

$sel.appendTo("<div></div>").insertAfter("#mydiv");

but that doesn't work either 但这也不起作用

$sel is just the select box, not the thing that wraps it. $sel只是选择框,而不是包装它的东西。 If you want that too, you can put that in a variable: 如果您也希望这样做,可以将其放在变量中:

var $div = $("<div></div>");
$div.append($sel).insertAfter("#mydiv");

Or of course there are a dozen other ways to do it, but this keeps everything nice and organized. 或当然还有其他十二种方法可以做到这一点,但这可以使一切保持井井有条。

Use jQuery .wrap() . 使用jQuery .wrap() Try this: 尝试这个:

var $sel = $("<select></select>");
$sel.append("<option>1</option");
$sel.wrap("<div></div>").parent().insertAfter("#mydiv");

DEMO 演示

Your code is fine with appendTo and no need to use wrap , but you are inserting the wrong element ie the select instead of the div that has wrapped the select. 您的代码可以使用appendTo很好,并且不需要使用wrap ,但是您要插入错误的元素,即select而不是包装了select的div。 You need to use $sel.parent() with insertAfter() 您需要将$sel.parent()与insertAfter()一起使用

Live Demo 现场演示

var $sel = $("<select></select>");
$sel.append("<option>1</option");
var $sel = $sel.appendTo("<div></div>");
$sel.parent().insertAfter("#mydiv");      //Insert the parent of select instead of select.

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

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