【问题标题】:Jquery.load() and script tags inside the file that we want to load我们要加载的文件中的 Jquery.load() 和脚本标签
【发布时间】:2017-01-12 19:12:20
【问题描述】:

嗯,这很奇怪,但很简单,当我尝试在页面更改主索引的某些内容之前加载时,我注意到出了点问题,因为它只显示了实际年份“2017”,现在我可以确认它,因为创建了两个文件 test1.html 和 test2.html 这发生了:

Test1.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script>
        $(document).ready(function() {
            $("#test").load("test2.html");
        });
    </script>
</head>
<body>
    <div id="test"></div>
</body>
</html>

Test2.html

aaaaaaaaaaaaaa<br>
<script>document.write(new Date().getFullYear())</script>

结果:

那么,我能做些什么来避免这种情况,并无后顾之忧地展示一切? 尝试制作单独的功能也不起作用...

编辑:

现在,有人告诉我使用 document.write 是问题所在,我的问题是这是一个简单的解决方案,声明一个 html 元素稍后写入它的内容有点不简单和繁重,所以,我的实际问题是知道 document.write 是否有任何轻量级的替代品?

【问题讨论】:

  • 如果您不想替换所有内容,请不要使用document.write
  • 如果我想在不使用选择器的情况下编写一些东西,该怎么办? @桑蒂
  • 我现在会尝试 eval() ......无论如何,谢谢!

标签: jquery html dynamic-loading script-tag


【解决方案1】:

我对自己的解决方案进行了硬编码以使一切变得更简单,我创建了一个带有名为 data-func 的数据属性的元素,后来我这样做了:

$(document).ready(function() { 
     var fncs = $('[data-func]');
     fncs.each(function () {
         $(this).text(window[$(this).data("func")]);
     });
});

功能:

function getYear() {
    return new Date().getFullYear();
}

还有元素:

<span data-func="getYear"></span>

仅此而已!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 2019-07-17
    • 2014-11-24
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多