views:

2824

answers:

2

I'm using jQuery to append some JavaScript when an item is expanded.

But the JavaScript code inside of the jQuery function is causing the rest of the jQuery code to explode.

$(this).parent('li').find('.moreInfo').append('<script>alert("hello");</script>');

What can I do to solve this problem?

+7  A: 

For the appending JavaScript problem use this:

        var str="<script>alert('hello');";
        str+="<";
        str+="/script>";

        $(this).parent('li').find('.moreInfo').append(str);

Otherwise a better option will be to wire-up li's click event:

 $("ul#myList li").click(function(){
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "url to your content page",
            data: "{}",//any data that you want to send to your page/service
            dataType: "json",
            success: function(msg) {
                $(this).find('.moreInfo').append(msg);
            }
        });
 });

Actually I don't know what language are you using. If you are using ASP.NET please read this blog by Dave.

TheVillageIdiot
A: 
$(document).ready(function() {
        $("ul").each(function() {
            var _list = this;
            $(_list).find("li").click(function() {
                var _listItem = this;
                $(this).animate({ height: 20 }, 300);
                $(this).append("<script type='text/javascript'>" + "$('.resultsParag').text('I am injected via JS and will not mess up the other JS you have written cause I am a good boy');" + "</" + "script>");
            });
        });
    });
Ali