从< input>中的值中删除类.标签 [英] Removing a class from value in an <input> tag

查看:70
本文介绍了从< input>中的值中删除类.标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个<input>标记,带有一些HTML作为值.我想删除所有具有强调"类的<span>,但仍将内容保留在<span>中.我也不想删除任何其他<span>.

I have an <input> tag with some HTML as the value. I want to remove any <span>s that have the class of "emphasis", but still retain the content in the <span>. I also don't want any other <span>s removed.

以下示例:

此:

<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/)...

I've tried using jQuery with this fiddle (https://jsfiddle.net/0xgx04pq/4/)...

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);
}

.emphasis {
  background: orange;
  font-weight: bold;
}

<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>

...但是它不起作用. content_after最终返回为"[object Object]",有什么想法吗?

...but it's not working. content_after ends up coming back as "[object Object]" Any ideas?

推荐答案

基本思路

//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.

other option is to just read .text() instead of .html() and it will strip all html.

这篇关于从&lt; input&gt;中的值中删除类.标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆