简体   繁体   English

如何使用JQuery append(),add()或appendTo()将对象附加到DOM元素?

[英]How to append an Object to a DOM Element with JQuery append(), add() or appendTo()?

I can't seem to get this working, even though I have the idea it is perfectly correct. 即使我认为它完全正确,我似乎也无法使它正常工作。 Consider the following code: 考虑以下代码:

<script type="text/javascript>
        ul = $(".qtrans_language_chooser");
        parent = ul.parent();
        activeLangLi = ul.children("li.active");

        parent.prepend('<ul class="qtrans_active_language"></ul>');
        activeLangUl = $(".qtrans_active_language");
        o = activeLangLi.appendTo(activeLangUl);
        activeLangLi.remove();
</script>

All I'm trying to do is add activeLangLi to the empty activeLangUl. 我要做的就是将activeLangLi添加到空的activeLangUl中。 But no matter if I use append(), appendTo() or add() it never shows up. 但是无论我使用append(),appendTo()还是add(),它都不会显示。

Remove this line: 删除此行:

activeLangLi.remove();

This removes the elements from the DOM. 这将从DOM中删除元素。 append and appendTo will move (not copy) the elements from the current location to the new one. appendappendTo会将元素从当前位置移动 (而不是复制)到新位置。 If you remove them afterwards, well, then they are gone. 如果以后再将它们remove ,那么它们就不见了。

You could also optimize your code to: 您还可以优化代码以:

var ul = $(".qtrans_language_chooser");
$('<ul class="qtrans_active_language"></ul>')
    .prependTo(ul.parent())
    .append(ul.children("li.active"));

Don't forget to use var . 不要忘记使用var

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

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