【问题标题】:yii2-multiple-input I can't get current rowyii2-multiple-input 我无法获取当前行
【发布时间】:2019-07-29 21:19:27
【问题描述】:

我正在使用yii2-multiple-input,在使用javascript事件beforeDeleteRow删除项目时一切都很好,如下所示。

jQuery('#wtabularbotellas').on('beforeDeleteRow',function(e, row, currentIndex) {
   // This throw the number of rows instead how do I get the current Index? 
   alert(currentIndex);    
});

但我无法捕获该行的 ID 号。我尝试使用row 对象和currentIndex 变量来执行此操作,但没有结果,因为后者只返回行数而不是我要查找的索引。

【问题讨论】:

    标签: javascript jquery yii2 widget tabular


    【解决方案1】:

    您使用的currentIndex实际上是多输入容器所在的当前索引。

    例如,如果您有5 输入并且您删除1,则当前索引将为4,它不是删除行的索引,因此这意味着currentIndex 不是实际索引该行的数量,但容器中的总行数,如果您期望如果您从5 行总数中删除第三行,它应该返回 3/2(取决于来自 0 或 @ 的起始索引987654330@) 那你就错了。

    我无法通过获取元素/行的实际行 ID 来猜测您真正想要完成的任务,尽管您可以这样做,但在您这样做之前您需要了解一些东西。

    将以下列表分别视为容器内的行和索引。

    | IDX | Element | ID  
    | 1   | input   | email-1
    | 2   | input   | email-2
    | 3   | input   | email-3
    | 4   | input   | email-4
    | 5   | input   | email-5
    

    如果你删除最后一行,新的索引将和之前一样,逻辑上应该没问题。

    | IDX | Element | ID  
    | 1   | input   | email-1
    | 2   | input   | email-2
    | 3   | input   | email-3
    | 4   | input   | email-4
    

    但是如果您删除第一行,并且您希望在删除第一行后其余索引将保留之前的索引,如下所示,

    | IDX | Element | ID  
    | 2   | input   | email-2
    | 3   | input   | email-3
    | 4   | input   | email-4
    | 5   | input   | email-5
    

    不行,删除后索引会被重置,如果每次删除第一个元素,总是得到索引1。

    因此,如果您仍想获取已删除行的行号,则应使用row 参数和.index() 函数row 参数将具有即将被删除的行的对象已删除。

    注意:以下示例均使用基本单列,请相应调整您的脚本

    $js = <<<JS
        jQuery('#wtabularbotellas').on('beforeDeleteRow',function(e, row,currentIndex) {
           //the index of the row removed 
           let removedIndex= row.index();
    
           //id of the input inside 
           let inputId = row.find(':input').attr('id');
           console.log("Index removed====>"+removedIndex, "Input id of the removed row input====>"+inputId);
        });
    JS;
    
    $this->registerJs($js, \yii\web\View::POS_READY);
    

    【讨论】:

    • 非常感谢。我想获得“真实索引”来验证 ajax 的操作。例如,如果用户尝试删除并且该行有子记录,我想在用户发布表单之前阻止这种情况,并显示一些错误消息。
    • 您应该不使用 HTML 索引,而应该在最初创建输入时使用输入 data 属性,如 data-has-child="true",并在删除时使用上面提到的方法只需将row.find(':input').attr('id');更改为row.find(':input').data('has-child');并立即拒绝删除或允许它@TomasGrecioRamirez在使用事件时不要使用ajax调用,因为您将无法返回truefalse那案子
    猜你喜欢
    • 2021-09-11
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 2015-07-31
    • 2020-08-05
    • 2022-10-18
    • 1970-01-01
    相关资源
    最近更新 更多