jQuery - 将 JavaScript 添加到 Div

13

我正在使用jQuery,在展开某个项目时添加了一些JavaScript

但是,jQuery函数内的JavaScript代码导致其余的jQuery代码失效。

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

我该怎么做来解决这个问题?


请发布HTML,并告诉添加脚本的目的。 - TheVillageIdiot
HTML在这里并不是特别适用,而javascript的目的是从远程源中提取信息。但是,我希望在需要时而不是在加载时获取站点上70多个项目的信息。 - Tim
但是你为什么想要将JavaScript附加到div上呢?你可以在单击时获取节点的内容并将其附加到div中或其中。 - TheVillageIdiot
因为如果页面上有JavaScript,它会导致来自远程源的请求,这意味着由于请求的总数而导致加载时间缓慢。通过按需拉取,我将不会看到相同的缓慢加载时间。 - Tim
4个回答

20

针对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,请阅读由Dave撰写的这篇博客


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

2
尝试在 /script 前面添加 \,这样可以解决你的问题。

0

可以尝试像这样

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接