简体   繁体   English

jQuery appendTo()到html()以允许替换

[英]JQuery appendTo() to html() to allow replace

I have the following 我有以下

$('.toggle_questions').appendTo('#'+sectionId).show();

Which works perfectly to append my div ( .toggle_questions ). 完美地附加我的div( .toggle_questions )。 However, I want it to replace rather than add each time. 但是,我希望每次替换而不是添加。

From my understanding this is done through html() rather than appendTo() ? 据我了解,这是通过html()而不是appendTo() I have only found examples adding simple <p> codes and not actual <div> 's 我只找到添加简单的<p>代码而不是实际的<div>的示例

I have changed it to this but it won't seem to do anything: 我已将其更改为此,但它似乎无能为力:

$('#'+sectionId).show().html($('.toggle_questions')).show();

The show() is needed as it is set to hidden to start with. 需要show() ,因为将其设置为隐藏开始。

Where have I gone wrong? 我哪里出问题了? Thanks! 谢谢!

I would save the content of $('.toggle_questions') on every occurrence and apply it like this: 我会在每次出现时保存$('.toggle_questions')的内容,并像这样应用它:

var content = $('.toggle_questions').html();
$('#' + sectionId).html(content).show()

It's a much cleaner code and easier to maintain. 这是一个更简洁的代码,更易于维护。

Try to pass html string in to .html() , 尝试将html字符串传递给.html()

$('#'+sectionId).html($('.toggle_questions').html()).show();

.html() wont accept jquery object as its parameter. .html()不会接受jquery对象作为其参数。

But appendTo() will move the original object. 但是appendTo()将移动原始对象。 If you want to do the same thing using .html() , then you have to remove it manually after setting the html string. 如果要使用.html()执行相同的操作,则必须在设置html字符串后手动将其删除。

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

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