您好,我现在正试图在添加文本字符串后再删除文本字符串。
我有一个处理手风琴的脚本,我的文本中有一些冗余。所以我想在打开或关闭手风琴行时添加和删除冗余文本。
这是我的代码:
var redundantText = "text text text <a href=\"#contact\">Contact Me</a> text text text";
$('#collapse_1').on('show.bs.collapse', function() {
$(".dropdown_collapse_1").addClass("dropdown-indicator");
$(".dropdown_collapse_1").removeClass("dropdown-collapsed");
$("#redundant_text_wrapper").append(redundantText);
});
$('#collapse_1').on('hide.bs.collapse', function() {
$(".dropdown_collapse_1").addClass("dropdown-collapsed");
$(".dropdown_collapse_1").removeClass("dropdown-indicator");
$("#redundant_text_wrapper").text().replace(redundantText, '');
});
附加工作正常,但text()。replace()没有。因此,如果我多次打开和关闭手风琴行,它总是附加redundantText但从不删除它,以便冗余文本变得更加冗余。
编辑: 改变了'redundantText&#39;到redundantText。仍然无法正常工作
EDIT2:
$("#redundant_text_wrapper").text($("#redundant_text_wrapper").text().replace(redundantText,''));
也没有帮助,它只删除链接,但文本保持
EDIT3:
$( "#redundant_text_wrapper").text(function(index, currentText) {
return currentText.replace(redundantText,'');
});
也只删除链接,文字保持
答案 0 :(得分:3)
应该是:
$( "#redundant_text_wrapper").text( $( "#redundant_text_wrapper").text().replace('redundantText','') ) ;
或者,如果您要替换所有出现次数:
$( "#redundant_text_wrapper").text( $( "#redundant_text_wrapper").text().replace(/redundantText/g,'') ) ;
答案 1 :(得分:0)
更改
$( "#redundant_text_wrapper").text().replace('redundantText','');
致:
$( "#redundant_text_wrapper").text().replace(redundantText,'');
删除变量周围的引号。这样它将被视为变量而不是字符串。
或
$("#redundant_text_wrapper").text($("#redundant_text_wrapper").text().replace(redundantText,''));
这样它首先得到文本而不是替换它并设置它。
答案 2 :(得分:0)
好的,我现在尝试了另一种方法:
var redundantText = "<span id=\"redundantText_wrapper\"> text text text <a href=\"#contact\">Contact Me</a> text text text</span>";
$('#collapse_1').on('show.bs.collapse', function() {
$(".dropdown_collapse_1").addClass("dropdown-indicator");
$(".dropdown_collapse_1").removeClass("dropdown-collapsed");
$("#redundant_text_wrapper").after(redundantText);
});
$('#collapse_1').on('hide.bs.collapse', function() {
$(".dropdown_collapse_1").addClass("dropdown-collapsed");
$(".dropdown_collapse_1").removeClass("dropdown-indicator");
$('#redundantText_wrapper').remove();
});
所以基本上我使用'after'而不是'append'并将文本放入带ID的范围内。现在我可以使用$('#ID')。remove();在关闭标签时摆脱它。