Подтвердить что ты не робот

JQuery - добавление JavaScript в Div

Я использую jQuery, чтобы добавить JavaScript, когда элемент расширяется.

Но код JavaScript внутри функции jQuery приводит к взрыву остальной части кода jQuery.

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

Что я могу сделать для решения этой проблемы?

4b9b3361

Ответ 1

Для проблемы с добавлением JavaScript используйте это:

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

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

В противном случае лучшим вариантом будет подключение события li:

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

На самом деле я не знаю, на каком языке вы работаете. Если вы используете ASP.NET, прочитайте этот блог Дэйв.

Ответ 2

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

Ответ 3

Попробуйте добавить \ до /script, и он должен решить вашу проблему.

Ответ 4

Можно попробовать как это

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