从字符串中间删除一个字符:不删除内部元素

ici*_*ing 9 html javascript string jquery

这个让我难过.我想从label元素中删除"+" .这是HTML:

 <label class="option" for="edit-attributes-21-33">
 <input type="radio" id="edit-attributes-21-33" name="attributes[21]" 
 value="33" checked="checked" class="form-radio"> 4 oz, +$15.00</label>
Run Code Online (Sandbox Code Playgroud)

我从这开始

$(".option").each(function(index, value) {

$(this).text( $(this).text().replace("+", ""));

})
Run Code Online (Sandbox Code Playgroud)

这将删除"+",但也会删除输入元素.那么我试过:

$(".option").each(function(index, value) {

var oldString = $(this).html();
var newString = oldString.replace("+", "");
console.log(oldString, newString);
$(this).text(newString);

})
Run Code Online (Sandbox Code Playgroud)

这会产生一个正确的html标记字符串,但它是一个字符串,并以这种方式传回DOM.我看到另一篇帖子有同样的问题,但没有解决方案.

Dar*_*eal 6

您可以使用代码来实现您想要的代码,.html()而不是.text():

$(".option").each(function(index, value) {
    var oldString = $(this).html();
    var newString = oldString.replace("+", "");
    console.log(oldString, newString);
    $(this).html(newString);
});
Run Code Online (Sandbox Code Playgroud)

这是JQuery .html()方法ref:https://api.jquery.com/html/

这是小提琴:https://jsfiddle.net/Darkseal/1c572Luw/

我还稍微修改了您的<input>结束标记,使其符合XHTML标准.

  • 这看起来与问题中的第二个代码块完全相同.你改变了什么? (2认同)
  • 包含对已更改内容和原因的解释是有帮助的.此外,在末尾没有斜杠的输入在html5中完全有效.我相信只有xhtml需要斜线. (2认同)
  • 我不太清楚你做了什么来使输入标签'符合HTML5',它是一个空元素 (2认同)