2017-03-06 8 views
3

古本のBCCode [img]{url}[/img]を取得し、そこからhtmlイメージを表示するには、this answerを変更しようとしています。私のコードスニペットに見られるように、私は[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に挿入しようとすると、無効なタグであるためブラウザは挿入しません。 1つの.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>

関連する問題