首页 > 解决方案 > 如何同时用 html 元素替换粗体、下划线等的文本?

问题描述

我在这里问一个先前的问题。大胆风格的解决方案是:

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>

那么,这里的解决方案是什么?

标签: javascriptjqueryhtmlcss

解决方案


在下划线过程 whena被赋予 的值之前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>


推荐阅读