开发者

How to add this html in a div, escaping the quotes?

I have some html code that i want to add dynamically to a div in a page.

My div is:

<div id="my_div" class="my_class">
</div>

This is my html code that i want to add to the above div, when i click on some button, using jquery onclick event.

<div id="content">
'Hello world 123' <br>
<img src='player.gif' width='200' height='100'>
Good morning...
Have a nice day...
</div>

So far, i tried this general way, when onclick event is invoked:

document.getElementById("my_div").innerHTML = 
'<div id="content">
    'Hello world 123' <br>
    <img src='pl开发者_Python百科ayer.gif' width='200' height='100'>
    Good morning...
    Have a nice day...
    </div>';

But as you can see, the code is error prone, as the quotes are mismatched and it breaks. How can i escape the quotes and add the content to div efficiently?


this should do the job:

document.getElementById("my_div").innerHTML = 
"<div id=\"content\">
    'Hello world 123' <br>
    <img src='player.gif' width='200' height='100'>
    Good morning...
    Have a nice day...
 </div>";

Instead i have escaped the double quotes around content.


You can just use backslash to escape it:

document.getElementById("my_div").innerHTML = 
'<div id="content">
    \'Hello world 123\' <br>
    <img src=\'player.gif\' width=\'200\' height=\'100\'>
    Good morning...
    Have a nice day...
    </div>';


Try this:

document.getElementById("my_div").innerHTML = 
'<div id="content">
    \'Hello world 123\' <br>
    <img src="player.gif" width="200" height="100">
    Good morning...
    Have a nice day...
    </div>';


With a simple example

http://jsfiddle.net/arjunshetty2020/MPYXS/

$(document).ready(function() {
    $("#btn").click(function() {
       document.getElementById("my_div").innerHTML ="<p id=\"test\">\"test1\" <br/>    test2<p>" ;
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜