我问了一个问题here .粗体风格的解决方案是:
var a;
var b;
$(document).ready(function() {
$("#convertBtn").on("click", function() {
$('#questionDisplay').text($("#questionEdit").val());
a = $("#questionDisplay").text();
$('#questionDisplay').html(a.split("**").join('</b>'));
b = a.split("**").join('</b>');
$('#questionDisplay').html(b.split('*').join('<b>'));
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="questionEdit" rows="5" style="width: 500px;">The user types here many *bold** and *secondBold** texts. The convert button should change the stars to html tags.</textarea>
<button id="convertBtn">Convert</button>
<p>Display: </p>
<p id="questionDisplay"></p>
现在,我想添加下划线样式的功能,并可能在未来添加更多样式。问题是带下划线的文本的第二个代码删除了第一个代码中完成的内容,如下所示:
var a;
var b;
$(document).ready(function() {
$("#convertBtn").on("click", function() {
$('#questionDisplay').text($("#questionEdit").val());
a = $("#questionDisplay").text();
$('#questionDisplay').html(a.split("**").join('</b>'));
b = a.split("**").join('</b>');
$('#questionDisplay').html(b.split('*').join('<b>'));
a = $("#questionDisplay").text();
$('#questionDisplay').html(a.split("__").join('</u>'));
b = a.split("__").join('</u>');
$('#questionDisplay').html(b.split('_').join('<u>'));
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="questionEdit" rows="5" style="width: 500px;">Now the user types here *bold** with _underlined__ texts. But the code of underlined removes the work done by the code of bold!</textarea>
<button id="convertBtn">Convert</button>
<p>Display: </p>
<p id="questionDisplay"></p>
那么,这里的解决方案是什么?
最佳答案
在 a
时下划线处理之前给出了 text
的值, 它不需要 tags
输入是为了使文本变粗。所以分配 a
与
a = $("#questionDisplay").html();
代替
a = $("#questionDisplay").text();
这将确保采取 <b>
元素,以便两者可以一起工作。
var a;
var b;
$(document).ready(function() {
$("#convertBtn").on("click", function() {
$('#questionDisplay').text($("#questionEdit").val());
a = $("#questionDisplay").text();
$('#questionDisplay').html(a.split("**").join('</b>'));
b = a.split("**").join('</b>');
$('#questionDisplay').html(b.split('*').join('<b>'));
a = $("#questionDisplay").html();
$('#questionDisplay').html(a.split("__").join('</u>'));
b = a.split("__").join('</u>');
$('#questionDisplay').html(b.split('_').join('<u>'));
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="questionEdit" rows="5" style="width: 500px;">Now the user types here *bold** with _underlined__ texts. But the code of underlined removes the code of bold!</textarea>
<button id="convertBtn">Convert</button>
<p>Display: </p>
<p id="questionDisplay"></p>
关于javascript - 如何同时用html元素替换文本为粗体、下划线等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54447426/