2015-04-15 42 views
9

这一个让我难住。我想从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> 

我开始用这个

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

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

}) 

这消除了 “+”,而且还剔除了input元素。于是我尝试:

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

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

}) 

这使得正确的HTML标记的字符串,但它是一个字符串,并传回给DOM的方式。我看到另一篇文章有​​同样的问题,但没有解决方案。

+0

相关但不完全重复:http://stackoverflow.com/questions/4106809/how-can-i-change-an-elements-text-without-changing-its-child -lelements –

+0

我不确定输入元素的含义是否被删除?给出一个例子,说明它最初是什么,在当前代码之后它变成了什么,以及你希望它做什么。 EX:原文:'Abc + 123 + 456'应该是'Abc 123 + 456',但这段代码返回'Abc 123 456' – Nitroware

回答

6

你可以实现你想用你的代码中使用.html()代替.text()什么:

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

这里的JQuery的.html()方法参照:https://api.jquery.com/html/

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

我也稍微修改您的<input>结束标记以使其符合XHTML标准。

+2

这看起来与问题的第二段代码非常相似。你有什么改变? –

+0

为什么downvote?此解决方案完美运作。它使用'.html()'而不是'.text()'。 – melancia

+0

他使用'.text()'而不是'.html()'。我只是修改代码而不是重写代码,以便他能够理解它们之间的差异,然后像'$(“。option”)。html($(“。option”)。html()。 “+”,“”))'或者类似的东西。我真的不明白downvote,我的回答是正确的。 – Darkseal

4

你在找什么叫做textNode。我给你的标签的ID,使其更容易,但器的原理仍然是其他选择相同:

var node = document.getElementById("example").childNodes[2]; 
node.nodeValue = node.nodeValue.replace("+", ""); 

With a simple demo.
你应该尝试jQuery中尽可能多的,你可以使用纯JS赞成。 Plain JS通常比jQuery快得多。

之后的评论,if you don't know the exact position of the textnode, check this

+1

如果他不确切知道textNode的位置怎么办? – jmartins

+1

已更新的答案。 – Martijn

+1

使用'香草Javascript'的绝佳解决方案。 – melancia

0

迟到的答案,只是为了展示使用jQuery的不同方法。

在这里,你会保持input状态,并且不会有替换你不想要的字符的风险。假设您在其他地方使用+,而不仅仅是label文本。

$(function() { 
    $('label.option').each(function() { 
     var label = $(this); 
     var input = $('input.form-radio', this); 
     var text = label.text(); 

     // Clean up the label contents. 
     label.empty();   

     // Replace the char occurrences. 
     text = text.replace(/\+/g, ""); 

     // Append both the input and the modified text. 
     label.append(input).append(text);   
    }); 
}); 

Demo

+0

你实际上可以完全移除'detach',下一行将文本设置为空就足够了 –

+0

非常真实,我已经更新了答案,谢谢! – melancia