从<input />标记

时间:2016-06-23 21:43:24

标签: javascript jquery html

我有一个<input>标记,其中包含一些HTML作为值。我想删除任何具有&#34;强调&#34;类的<span>,但仍保留<span>中的内容。我也不想删除任何其他<span>

以下示例:

此:

<input type="hidden" name="answer" id="answer" value="<span class="emphasis"><div class="fraction_display"><span class="numer_display">21</span><span class="bar_display">/</span><span style="border-top-color: green;" class="denom_display">23</span></div></span>"

最终应该是:

<input type="hidden" name="answer" id="answer" value="<div class="fraction_display"><span class="numer_display">21</span><span class="bar_display">/</span><span style="border-top-color: green;" class="denom_display">23</span></div>"`

我尝试过使用jQuery(https://jsfiddle.net/0xgx04pq/4/)...

&#13;
&#13;
function remove_emphasis_class (){
  var content = $('#answer').val(answer);
  var content_after = content.filter('span.emphasis').contents().unwrap();
  $('#answer').val(content_after);
  alert(content_after);
}
&#13;
.emphasis {
  background: orange;
  font-weight: bold;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="hidden" value="2 + 5 = <span class='emphasis'>7</span>" name="answer" id="answer">
<br><br>
<button onclick="remove_emphasis_class();">Remove Class</button>
&#13;
&#13;
&#13;

......但它没有用。 content_after最终会回复为&#34; [object Object]&#34;有什么想法吗?

3 个答案:

答案 0 :(得分:1)

基本理念

//using string instead of reading value of the input aka var str = $(".foo").val();
var str = "2 + 5 = <span class='emphasis'>7</span>";
//convert the string to html
var temp = $("<div>").html(str);
//find the span and unwrap it
temp.find(".emphasis").contents().unwrap();
//get the html string without the span
var updated = temp.html();
//display it
console.log(updated);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

其他选项是只读取.text()而不是.html(),它将删除所有html。

答案 1 :(得分:1)

输入值中可能存在emphasis类的多个span元素的一种方法可以是这样的;

var tempDir = document.createElement("div"),
        inp = document.getElementById("answer"),
    els2del,
    content = "";
tempDir.innerHTML = inp.value;
els2del = tempDir.querySelectorAll("span[class = 'emphasis']");
for (var i = 0; i < els2del.length; i++){
  content += els2del[i].innerHTML;
}
inp.value = content;
console.log(inp.value);
<input type="hidden" name="answer" id="answer" value="<span class='emphasis'><div class='fraction_display'><span class='numer_display'>21</span><span class='bar_display'>/</span><span style='border-top-color: green;' class='denom_display'>23</span></div></span>">

答案 2 :(得分:0)

试一试:

function remove_emphasis_class (){
        var answer = document.querySelector('#answer').value;
    var div = document.createElement("div");
    div.innerHTML = answer;
        var selector = div.querySelector('.emphasis');
    var newContent = selector.innerHTML;
    div.querySelector('.emphasis').outerHTML = newContent;
    console.log(div.innerHTML);
}