jQuery中使用.html()方法后无法保留#notify原有内容的问题咨询
如何在jQuery中保留元素原有内容并添加新内容
jQuery的.html()方法本身就是用来替换目标元素内部的全部HTML内容的,所以你直接传入新字符串时,原有内容会被覆盖,这是该方法的预期行为。
如果想要保留原有内容并添加新内容,有几种简单的解决方式:
使用
.append()方法,将新内容追加到元素内部的末尾:$('#notify').append('Want to get notified of single woman living near you?').slideDown();若需要把新内容放在原有内容的前面,改用
.prepend()方法:$('#notify').prepend('Want to get notified of single woman living near you?').slideDown();如果你一定要用
.html()方法,可以先获取元素原有内容,拼接新内容后再设置:const originalContent = $('#notify').html(); $('#notify').html(originalContent + 'Want to get notified of single woman living near you?').slideDown();
另外注意你代码里的引号是中文符号‘’,实际开发中要改用英文引号''或"",避免出现语法错误。
内容的提问来源于stack exchange,提问作者Alejandro Alarcon
相关产品推荐
相关产品推荐

