2015-04-15 45 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