简体   繁体   中英

jQuery append html with scripts

I need some help with jQuery.

When i'm trying to get html with embded js page content via $.get, it's works good. But when i'm trying to append it to some div, all scripts are removing.

In a console its look fine when i'm doing smthing like this

$('.my_div').html() + '<script>alert("text")</script>'

but when i'm doing

 $('.my_div').html($('.my_div').html() + '<script>alert("text")</script>')

script is running and removing

How can i append html+js code to div without running and removing?

Thanks!

UPD:

My example :

index.html

...

<div class="masonry">
    <div class="a1">
        <p>text</p>
        <script>alert('example')</script>
    </div>
    <div class="a1">
        <p>text</p>
        <script>alert('example')</script>
    </div>
    <div class="a1">
        <p>text</p>
        <script>alert('example')</script>
    </div>
</div>

...

<script>

$.get('get_news.php',function(response){

    $('.masonry').append(response);

});
</script>

...

get_news.php

    <div class="b1">
        <p>text</p>
        <script>alert('example1')</script>
    </div>
    <div class="b1">
        <p>text</p>
        <script>alert('example1')</script>
    </div>
    <div class="b1">
        <p>text</p>
        <script>alert('example1')</script>
    </div>

...

And i'm going to get

<div class="masonry">
    <div class="a1">
        <p>text</p>
        <script>alert('example')</script>
    </div>
    <div class="a1">
        <p>text</p>
        <script>alert('example')</script>
    </div>
    <div class="a1">
        <p>text</p>
        <script>alert('example')</script>
    </div>

    <div class="b1">
        <p>text</p>
        <script>alert('example1')</script>
    </div>
    <div class="b1">
        <p>text</p>
        <script>alert('example1')</script>
    </div>
    <div class="b1">
        <p>text</p>
        <script>alert('example1')</script>
    </div>

</div>

How can i do it?

That's the default behavior of .html() - it will strip out scripts and eval them while appending content to the DOM. jQuery even provides $.parseHTML which defaults to stripping out scripts without evaluating them to prevent against XSS.

If you're already executing a script in the page, the vast majority of the time you can just put your code in the same script. But if you really want/need to append a new script to the page, you can do it through append :

$('.my_div').append($('<script>', { text: 'alert("foo");' }));

Fiddle

You can use append if you don't want to remove the original content. As for stop the script tag from executing, one way is to change to script type to "text/html" or use html escape function.

http://jsfiddle.net/R5xad/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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