这是给定的格式:
how are <a href="#" class="frnd_class">Piyush</a>you fine and you <a href="#" class="frnd_class">Praveen</a>
而且,我需要通过使用jquery操作或替换html来实现以下格式:
<span>how are</span> <a href="#" class="frnd_class">Piyush</a> <span>you fine and you</span> <a href="#" class="frnd_class">Praveen</a>
答案 0 :(得分:0)
尝试使用.contents()
,.each()
,.html()
,$.trim()
,String.prototype.replace()
$("#pred_ques").on("blur", function() {
var div = $("<div />").html($(this).val());
div.contents().each(function(i, el) {
var text = el.nodeValue,
re = /\w+/i;
if (el.nodeType === 3 && re.test(text)) {
div.html(function(_, html) {
return html.replace(text, ($("span", el.parentElement).length ? " " : "") + $("<span />", {
html: $.trim(text)
})[0].outerHTML + " ")
});
}
});
$("#pred_ques_1").val($(div)[0].innerHTML)
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="text" id="pred_ques" name="pred_ques" value='how are <a href="#" class="frnd_class">Piyush</a>you fine and you <a href="#" class="frnd_class">Praveen</a>'>
<input type="text" id="pred_ques_1" name="pred_ques_1" value=''>
&#13;
jsfiddle http://jsfiddle.net/5a9yft7h/2/