Javascript jquery重置追加()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3452289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery reset append()
提问by DGT
How can I reset after append() or before()? Please help. Many thanks in advance.
如何在 append() 或 before() 之后重置?请帮忙。提前谢谢了。
if((#tag_id).text() == 'something'){
$(#tag_id).before("x");
}
// I want to reset the #tag_id to empty
$(#tag_id).val(''); // this doesn't work
回答by user113716
Your code example uses .before(). In this case, it would be better if .before()was given an element around xinstead of just the text.
您的代码示例使用.before(). 在这种情况下,如果.before()在周围提供一个元素x而不仅仅是文本会更好。
Then you could do this:
那么你可以这样做:
// Wrap the "x" that you're inserting with <span> tags
$('#tag_id').before('<span>x</span>');
// Use .prev() to reference the new <span> and remove it
$('#tag_id').prev().remove('span');?????????
Remember that using .before()does not place anything insidethe #tag_id, but instead places it beforethe #tag_id.
请记住,使用.before()不放置任何物品里面的#tag_id,而是放在它面前的#tag_id。
If you meant for the content to go inside#tag_idbut at the beginning, you would use .prepend().
如果您想让内容进入内部#tag_id但在开始时,您将使用.prepend().
If your code is using .append(), one option would be to keep a reference to the element you're appending, and use that to remove it later.
如果您的代码正在使用.append(),一种选择是保留对您要附加的元素的引用,然后使用它来删除它。
var $appendElem = $('<div>some appended element</div>');
$appendElem.appendTo('#tag_id');
Then you can remove it via the same reference.
然后您可以通过相同的引用将其删除。
$appendElem.remove();
// or
$appendElem.detach();
回答by Sarfraz
If you want to remove the html inside of it, use:
如果要删除其中的 html,请使用:
$('#tag_id').html('');
If you want to remove the idattribute, use the removeAttr:
如果要删除该id属性,请使用removeAttr:
$('#tag_id').removeAttr('id');
More Info:
更多信息:
回答by Nick Craver
If there are no handlers you can use .html()like this:
如果没有处理程序,您可以.html()像这样使用:
$('#tag_id').html('');
However if there are any event handlers or data on any objects in there you should use .empty()instead, like this:
但是,如果其中的任何对象上有任何事件处理程序或数据,则应.empty()改为使用,如下所示:
$('#tag_id').empty();
.html('')won't clean up data/event handlers in $.cachewhere .empty()and .remove()will, if you're unsure, use .empty()to avoid potential memory leaks.
.html('')不会清理数据/事件处理程序在$.cache哪里.empty(),并.remove()会,如果您不确定,使用.empty(),以避免潜在的内存泄漏。
回答by dale
Is this what you want?
这是你想要的吗?
$("#tag_id").html("");

