$(document).ready() 中的函数调用 vs $(document).ready(function() {})

问题描述 投票:0回答:1

我正在使用 displayRows() 函数使用 document.ready 添加表体。它的语法工作正常: $(document).ready(function() 如下

'$(document).ready(function() {
 function displayRows(){
var catRow = $('<tr class="category-row">'
+ '<th>'
+...........
+ '</th>'                                                         + '</tr>');
$('#cat tbody').append(catRow);
}
});`

但是当我删除下面的 function() 时,该表没有被附加。

`$(document).ready(
function displayRows(){
var catRow = $('<tr class="category-row">'
+ '<th>'
+...........
+ '</th>'                                                         + '</tr>');
$('#cat tbody').append(catRow);
}
});`

任何人都可以解释为什么它在下面的情况下不起作用。

我希望在这两种情况下它应该发挥相同的作用。由于 document.ready() 需要在其中传递一个函数。在第二种情况下,displayRows() 函数仍然作为函数传递给 document.ready。

javascript jquery dom-events
1个回答
0
投票

您直接将 displayRows() 传递给 $(document).ready(),这意味着 displayRows() 被视为就绪处理程序本身。仅当 displayRows() 定义为不带参数并且在 DOM 准备好后立即执行时,这才有效。

实现这项工作的一个选择是:

$(document).ready(function() {
    function displayRows(){
        var catRow = $('<tr class="category-row">'
            + '<th>'
            + '...'
            + '</th>'
            + '</tr>');
        $('#cat tbody').append(catRow);
    }
    
    displayRows();
});

另一种方法是直接传递 displayRows() 作为就绪处理程序:

function displayRows(){
    var catRow = $('<tr class="category-row">'
        + '<th>'
        + '...'
        + '</th>'
        + '</tr>');
    $('#cat tbody').append(catRow);
}

$(document).ready(displayRows);
© www.soinside.com 2019 - 2024. All rights reserved.