【问题标题】:Laravel: Generated buttons with loop (How to tell which one is click)Laravel:生成的带有循环的按钮(如何判断哪个是点击)
【发布时间】:2020-07-03 22:13:51
【问题描述】:

你好,Stockoverflow, 希望你一切都好,

你能再次帮助我使用 Laravel/Ajax 吗?

从下面给定的代码中,我生成了图片中显示的表格, 我想要完成的是在单击按钮时保存每一行, 我知道足够多的 ajax 来进行保存,问题是我如何告诉 ajax 和 jquery 哪个行按钮被单击以及哪个文本输入具有该值,因为文本输入和按钮是使用循环/数组生成的?

谢谢。

            if($list_factors)
        {
            foreach ($list_factors as $key => $list_factor) {
               // dd($list_factors);
                $output.='<tr>'.
                '<td>'.$list_factor->id.'</td>'.
                '<td>'.$list_factor->factor_description.'</td>'.
                '<td><input type="text" id="score" /></td>'.
                '<td><button class="btn btn-info" id="submitScore">OK</button></td>'.
                '</tr>';

            }
            return Response($output);
        }

【问题讨论】:

  • 如何捕获点击,显示事件处理程序代码。你在使用任何js 库或类似的东西吗?
  • 你好,其实我还没有启动点击功能,但是我会用jquery。

标签: arrays ajax laravel loops


【解决方案1】:

首先,您不能在循环内生成的按钮中使用id="submitScore" 属性,因为id 必须是唯一的。相反,您可以使用class="submitScore"。另外,你不能在input中使用id="score",使用class="score"既然你要使用jQuery,那么你可以试试这样的:

// Register the event handler on 'submitScore' class of button
$('button.submitScore').on("click", function(e) {
    var row = $(this).closest('tr');
    var inputValue = row.find('.score').val();
    console.log(inputValue);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
    <tr>
        <td><input class='score' /></td>
        <td><button class='submitScore'>OK</button></td>
    </tr>
    <tr>
        <td><input class='score' /></td>
        <td><button class='submitScore'>OK</button></td>
    </tr>
 </table>

【讨论】:

  • 谢谢,现在我学到了关于 id 和 class 的新信息。明天我会试试你的答案:) 保持安全......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-02
  • 2010-10-18
  • 2021-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多