2017-03-06 80 views
3

我正在尝试修改this answer以取得经典的BCCode [img]{url}[/img]并从中显示html图像。正如我的代码片段所见,我已经能够成功地做出类似于[b]text[/b]的事情。但由于某些原因,[img][/img]图像根本不显示。如何使用“.replace()”和“.html()”将纯文本转换为图像标签?

那么,如何使用.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>

回答

2

你的代码的问题是替换字符串中的两个部分进行标记。当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>