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?
In JavaScript, we can append HTML code to a div using innerHTML and insertAdjacentHTML.
First, select the div element which need to be copy into another div element. Select the target element where div element is copied. Use the append() method to copy the element as its child.
The insertAfter() method is an inbuilt method in jQuery that is used to insert some HTML content after a specified element. The HTML content will be inserted after each occurrence of the specified element. Syntax: $(content).insertAfter(target)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With