【问题标题】:Does Javascript / JQuery code need to be below other HTML code?Javascript / JQuery 代码是否需要低于其他 HTML 代码?
【发布时间】:2014-09-08 21:03:13
【问题描述】:

我有这个 JQuery 代码和 JS 代码下方的链接。如果链接在 JS 代码下方似乎不起作用,但如果 JS 代码在链接下方则可以。

如何让它与链接上方的 JS 代码一起工作?我需要这样做,因为我在使用 PHP 包含的文件中有 JS 代码。

<div id="EditPage" class="EditPagePopup">
<iframe id="EditPageFrame" width="100%" height="80%" src=""></iframe>
<a id="JQueryClose">&#215;</a>
</div>
<script>
$("a#EditPageLink").click(function (e) {
    alert("f");
    e.preventDefault();
    $("#EditPageFrame").attr("src", $(this).attr("value"));
    $("a").removeClass("active");
    $(this).addClass("active");

    JQueryPopup('#EditPage');
});
</script>

<a id="`EditPageLink`" href="#" value="editcustomer.php?seq='.$customer["sequence"].'"

【问题讨论】:

  • $(document).ready包装
  • 把script标签放到body标签外面,放到head标签里。它解决了问题
  • id 属性中的刻度是怎么回事?您可能想删除这些。

标签: javascript jquery


【解决方案1】:

当代码在 html 之上时,它可能会在 DOM 完全加载之前被执行。建议将依赖 DOM 的 javascript 放在页面底部以避免此问题。

【讨论】:

    【解决方案2】:

    不需要,但建议这样做。阅读this previously asked question

    您绝对应该做的是使用 jQuery 的 ready function 来确保在附加事件之前 DOM 已经完成加载。例如:

    $(function() {
        $("a#EditPageLink").click(function (e) {
            alert("f");
            e.preventDefault();
            $("#EditPageFrame").attr("src", $(this).attr("value"));
            $("a").removeClass("active");
            $(this).addClass("active");
    
            JQueryPopup('#EditPage');
        });
    });
    

    这样做将正确附加事件,无论您的脚本标记出现在 html 中的什么位置。

    【讨论】:

      【解决方案3】:

      将脚本一直放在底部已成为惯例,因为这样浏览器可以渲染页面并最后加载和运行脚本。

      它曾经是 head 标签内的所有脚本,在那个时候。但实际上,您可以将脚本放在任何地方,将所有内容放在一个位置(顶部或底部)使您的标记具有可读性和可维护性。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-06
        • 2017-10-22
        • 1970-01-01
        • 2017-07-31
        • 2012-08-04
        相关资源
        最近更新 更多