繁体   English   中英

如何使用“.replace()”和“.html()”将纯文本转换为图像标记?

[英]How can I use “.replace()” and “.html()” to turn plaintext into an image tag?

我试图修改这个答案 ,以便采取经典的BCCode [img]{url}[/img]并从中显示一个html图像。 如我的代码片段所示,我已经能够成功地执行与[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尝试将<img src="">插入到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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM