【问题标题】:How can I use ".replace()" and ".html()" to turn plaintext into an image tag?如何使用“.replace()”和“.html()”将纯文本转换为图像标签?
【发布时间】:2017-07-26 17:18:45
【问题描述】:

我正在尝试修改 this answer 以获取经典的 BCCode [img]{url}[/img] 并从中显示 html 图像。从我的代码 sn-p 中可以看出,我已经能够成功地用[b]text[/b] 做类似的事情。但是,由于某种原因,使用 [img][/img] 时,图像根本不会显示。

那么,如何使用.replace() 和.html() 将明文转为图片标签?

$('#boldText').click(function() {
  $('#bold').html(function(i, htm) {
    return htm.replace(/\[b\]/g, '<b>');
  }); // Replace opening tag
  $('#bold').html(function(i, htm) {
    return htm.replace(/\[\/b\]/g, '</b>');
  }); // Replace closing tag
});
$('#createImage').click(function() {
  $('#image').html(function(i, htm) {
    return htm.replace(/\[img\]/g, '<img src="');
  }); // Replace opening tag
  $('#image').html(function(i, htm) {
    return htm.replace(/\[\/img\]/g, '">');
  }); // Replace closing tag
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="bold">
  [b]bold text[/b]
</p>
<button id="boldText">
  Make above text bold
</button>
<p id="image">
  [img]http://i.imgur.com/mFJlvPf.jpg[/img]
</p>
<button id="createImage">
  Make above text into image
</button>

【问题讨论】:

    标签: javascript jquery html regex replace


    【解决方案1】:

    您的代码的问题在于将字符串替换为两部分的标记。当javascript试图将&lt;img src="或"&gt;插入html时,浏览器不会插入它,因为它是无效的标签。在一个 .html() 函数中使用两个 .replace() 字符串作为链。

    $('#boldText').click(function() {
      $('#bold').html(function(i, htm) {
        return htm.replace(/\[b\]/g, '<b>').replace(/\[\/b\]/g, '</b>');
      }); 
    });
    $('#createImage').click(function() {
      $('#image').html(function(i, htm) {
        return htm.replace(/\[img\]/g, '<img src="').replace(/\[\/img\]/g, '">');
      }); 
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p id="bold">
      [b]bold text[/b]
    </p>
    <button id="boldText">
      Make above text bold
    </button>
    <p id="image">
      [img]http://i.imgur.com/mFJlvPf.jpg[/img]
    </p>
    <button id="createImage">
      Make above text into image
    </button>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-21
      • 1970-01-01
      • 2010-09-22
      • 2011-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多