0

恐怕很多人会觉得我的问题很琐碎,但我需要问它。

(应很多人的要求,我已经编辑了代码,以便您可以重现它。)

我在脚本标签中定义了一个 JavaScript 全局变量,如下所示:

<!DOCTYPE html>
<html lang="en">
<head> 
<!--JQUERY-->
<script type="text/javascript" src="js_test/jquery-1.8.2.min.js" ></script>

<script type="text/javascript">
    var store_categories = []; 
    function init_filtering() {
        store_categories.push('data');
        alert ("alert1: "+ store_categories);
    }
</script>


<script type="text/javascript">$( init_filtering );</script>

</head>  
<body>

<script type="text/javascript">
    alert ("alert2: "+ store_categories);
</script>

</body>
</html>

加载页面时,alert2 首先出现空白值,然后出现 alert1 显示“数据”作为值。

谁能告诉我发生了什么?

4

2 回答 2

2

alert ("alert2: "+ store_categories);立即运行。

$( init_filtering );是在 DOM 准备好时(即解析后)运行的一种无用的快捷方式(参见self-documenting code )。init_filtering</html>

于 2012-11-02T16:25:09.390 回答
1

$(function() {...})执行等效于$.ready() 而您的内联脚本将在文档中解析后立即执行。

这意味着您指定的函数将延迟到页面加载。

空数组 toString 是一个空字符串,这就是为什么您在 first 中什么也看不到的原因alert

于 2012-11-02T16:25:30.943 回答