【问题标题】:jQuery function not firing after button click, but does for other eventsjQuery函数在按钮单击后不触发,但对于其他事件
【发布时间】:2026-01-26 00:10:01
【问题描述】:

我有一个使用 jQuery UI sortable 函数具有可拖动行的 HTML 表。它有一个显示行号的索引列。

如果用户将一行从表格底部拖到顶部,则行号列中的值会更新以显示正确的值。这目前工作正常。

我现在希望能够单击一个按钮,该按钮插入一行并重新计算表中所有行的行号。

我已经能够将该行添加到表格的顶部,但是在触发另一个事件之前行号不会更新,例如将一行拖到新位置或再次单击按钮。

请参阅下面的代码,非常感谢任何帮助。

html

<table id="sort" class="grid">
    <thead>
        <tr><th class="index">Index</th><th>Name</th></tr>
    </thead>
    <tbody>
        <tr><td class="index">1</td><td>Zippy</td></tr>
        <tr><td class="index">2</td><td>George</td></tr>
        <tr><td class="index">3</td><td>Bungle</td></tr>
        <tr><td class="index">4</td><td>Geoffrey</td></tr>
    </tbody>
</table>

jQuery

    $(document).ready(function () {

        $("#sort tbody").sortable({
            helper: fixHelperModified,
            stop: updateIndex
        }).disableSelection();

        var fixHelperModified = function (e, tr) {
            var $originals = tr.children();
            var $helper = tr.clone();
            $helper.children().each(function (index) {
                $(this).width($originals.eq(index).width())
            });
            return $helper;
        },
        updateIndex = function (e, ui) {
            $('td.index', ui.item.parent()).each(function (i) {
                $(this).html(i + 1);
            });
        };

        $('#AddRowButton').click(function () {
            var newRow = '<tr><td class="index">1</td><td>New Row</td></tr>';
            $(newRow).insertBefore('table > tbody > tr:first');
            updateIndex;
        });

    });

【问题讨论】:

  • 调用函数..updateIndex()
  • @RajaprabhuAravindasamy 感谢您的评论,我已将其更改为 updateIndex() 但这会返回以下错误 Unable to get property 'item' of undefined or null reference 。这是因为updateIndex() 需要两个参数(e,ui)

标签: jquery html-table jquery-ui-sortable


【解决方案1】:

在您传递给 jQuery 的 click 方法的函数中,您没有调用 updateIndex 函数 - 它缺少一对括号,应该是 updateIndex()

【讨论】:

  • 感谢您的快速回复,我已将其更改为 updateIndex() 但这会返回以下错误 Unable to get property 'item' of undefined or null reference 。这是因为updateIndex() 需要两个参数(e,ui)
  • 是的。您可以传递一个空对象作为第一个参数,因为它无论如何都没有使用,但第二个需要是一个与 jQuery ui 可排序组件使用的 ui 对象匹配的对象
最近更新 更多