简体   繁体   English

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

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

I am attempting to modify this answer in order to take classic BCCode [img]{url}[/img] and display an html image from it. 我试图修改这个答案 ,以便采取经典的BCCode [img]{url}[/img]并从中显示一个html图像。 As seen in my code snippet, I have been able to successfully do something similar with [b]text[/b] . 如我的代码片段所示,我已经能够成功地执行与[b]text[/b]类似的操作。 For some reason, though, with [img][/img] the image doesn't display at all. 但是,出于某种原因,使用[img][/img]图像根本不显示。

So, how can I use .replace() and .html() to turn plaintext into an image tag? 那么, 我如何使用.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> 

Problem of your code is in replacing string to tag in two part. 您的代码问题在于将字符串替换为标记两部分。 When javascript trying to insert <img src=" or "> into html, browser doesn't insert it because it is invalid tag. 当javascript尝试将<img src="">插入到html中时,浏览器不会插入它,因为它是无效标记。 Use both of .replace() after string for chain in one .html() function. 在一个.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