【问题标题】:What is the difference between these two jQuery usage这两个jQuery用法有什么区别
【发布时间】:2012-09-08 07:44:17
【问题描述】:

我是 jquery 入门者,如果写错了请见谅:)

我只是想知道为什么将内容放在不同的位置会使这个脚本工作,尽管我认为脚本保存在文档的head 部分。请解释一下这个概念。

工作代码

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Example 2</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

</head>

<body>

<p>
</p>

<script type="text/javascript">
jQuery("p").html("Check if jQuery Supports Ajax method : "+ jQuery.support.ajax );
</script>

</body>
</html>

不工作

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Example 2</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
jQuery("p").html("Check if jQuery Supports Ajax method : "+ jQuery.support.ajax );
</script>
</head>

<body>

<p>
</p>

</body>
</html>

【问题讨论】:

标签: javascript jquery html logic concept


【解决方案1】:

在第二种情况下,代码在 &lt;p&gt; 被解析到 DOM 树之前执行,所以虽然它仍然可以工作,但没有地方可以将输出文本放入其中。换句话说,jQuery("p") 不匹配任何元素,所以.html()“什么都不做”。

您可以通过等待 DOM 完全解析来解决此问题:

jQuery(function() {
    jQuery("p").html(...);
});

或使用不依赖于现有&lt;p&gt; 的输出机制,例如alert()console.log()

【讨论】:

    【解决方案2】:

    好吧,您的浏览器似乎首先加载了&lt;head&gt; 部分,因此在第二个示例中没有p 元素。

    在这两种情况下,您都应该将代码包装在 $(function(){ ... }) 中。

    【讨论】:

      【解决方案3】:

      如果您将脚本放在&lt;body&gt; 元素之前,它会在加载/解析DOM 树之前执行。 &lt;p&gt; 元素因此不存在且无法找到。你可以:

      • 将脚本放在&lt;body&gt; 标记之后(如您的第一个示例)

      • 或者您可以在ready 事件被触发后调用您的函数:

        $(document).ready(function() {
          jQuery("p").html("Check if jQuery Supports Ajax method : "+ jQuery.support.ajax );
        });
        

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-12
        • 2016-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多