这是一小段代码:
var $el = $("#something").find(".test");
if (!$el.length) {
$("#something").append('<div class="test">somecontent</div>');
} else {
$el.replaceWith('<div class="test">somenewcontent</div>');
}
我找不到方法 appendOrReplaceWith 或任何类似的方法。
我有什么想法可以让它更短吗?
我相信:
$("#something").appendOrReplace('<div class="test">sometext</div>');
会更容易阅读,但目前还没有这样的方法。
最佳答案
只需先删除它,然后再追加。
$(".test").remove();
$("#something").append('<div class="test">somecontent</div>');
关于javascript - jQuery 追加元素,如果它不存在,否则替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22971580/