r0d*_*ney 2 javascript jquery jquery-ui
所以我在jquery-ui文档中看到了这段代码,我想知道为什么所有的语句都包含在内 $(function() {...});
jquery文档说$()增强了它中的对象,但我不明白为什么我们需要它.这是一项惯例还是实际上有意义?
<script>
$(function() {
$( "#draggable" ).draggable();
$( "#droppable" ).droppable({
drop: function( event, ui ) {
$( this )
.addClass( "ui-state-highlight" )
.find( "p" )
.html( "Dropped!" );
}
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
$(function() {});就所有意图和目的而言,都是一样的$(document).ready(function() {});; 虽然我相信在文件准备好之前会稍微调用它.
它的作用是在文档创建完成后调用函数内的代码.这就是在函数加载时创建的所有DOM树.这允许您在知道那些对象将在那时创建时安全地操作DOM.
这是一个例子:
<script>
//This code is called straight away, your DOM hierarchy may not
//be complete and the object #draggable may not have been created yet,
//as such draggable() may not work properly.
$( "#draggable" ).draggable();
//This code is called once the DOM tree is complete,
//as such you know all your objects have been created
$(function() {
$( "#draggable" ).draggable();
$( "#droppable" ).droppable({
drop: function( event, ui ) {
$( this )
.addClass( "ui-state-highlight" )
.find( "p" )
.html( "Dropped!" );
}
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
有关更全面的说明,请参阅jQuery文档
| 归档时间: |
|
| 查看次数: |
93 次 |
| 最近记录: |