jQuery get text 包括单引号 using text() 无法正确显示

jQuery get text include single quote using text() doesn't show properly

本文关键字:text 显示 using 包括单 get jQuery      更新时间:2023-09-26

所以我想在单击按钮时将div的文本显示为输入值。但是,如果文本包含单引号,则无法正确显示。

<div id="content_comment">It's Yours!</div>
<button id="btn_comment_edit">Edit</button>     
// jQuery
$('.btn_comment_edit').click(function(){
    $('#content_comment').replaceWith("<form method='post'><input type=text value='"+$('#content_comment').text()+"'></form>")
});
// result 
// It'  (doesn't show after single quotes)

它应该It's Yours!输入值中。如何用单引号显示整个语句?

你可以做这样的事情

 $('#content_comment').replaceWith("<form method='post'><input type=text value='''' +$('#content_comment').text()+'''></form>")

问题在于单引号和双引号的用法。您也在使用.btn_comment_edit而不是#btn_comment_edit。尝试如下。

$('#btn_comment_edit').click(function () {
    $('#content_comment').replaceWith('<form method=post><input type=text value="' + $('#content_comment').text() + '"></form>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content_comment">It's Yours!</div>
<button id="btn_comment_edit">Edit</button>

这就是编码的方式。

$('.btn_comment_edit').click(function(){        
    var a = $('#content_comment').text();
    a = addslash(a);           
    $('#content_comment').replaceWith("<form method='post'><input type=text value='"+a+"'></form>")
});
function addslash(iid){
    str=iid.replace(/"/g,''"');
    str=iid.replace(/'/g,'''');
    return str;
}