13

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?

4
  • will you please post html and tell the purpose of appending the script? Commented Jun 7, 2009 at 5:19
  • The HTML isn't overly applicable here and the purpose of the javascript is to pull information from a remote source. But instead of pulling this information for the 70 plus items on my site at load, I'd prefer to pull it on demand. Commented Jun 7, 2009 at 5:20
  • but you why do you want to append javascript to div? you can fetch the content of the node on click and append that to the div or into it. Commented Jun 7, 2009 at 5:46
  • Because if the javascript is on the page it causes a request from a remote source which means slow load times because of the total number of requests. By pulling on demand I would not see the same slow load time. Commented Jun 7, 2009 at 5:50

4 Answers 4

20

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.

Sign up to request clarification or add additional context in comments.

Comments

3
$(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>");
            });
        });
    });

Comments

2

Try adding a \ before /script and it should resolve your issue.

Comments

0

Can try like this

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.