【问题标题】:How to put items from table into an array jquery如何将表中的项目放入数组jquery
【发布时间】:2016-10-17 04:39:05
【问题描述】:

假设我有一个通过 foreach 循环迭代的表,并且项目来自数据库。

例如,

<table>
    <?php while($row = $result->fetch_assoc()){?>
    <tr>
      <td><?php echo $row['id'] ?></td>
      <td><?php echo $row['name'] ?></td>
      <input type="button" name="add" />
    </tr>
    <?php }?>
</table>

现在每一行中都有一个按钮可以迭代,当我单击添加时,我想要的是将特定项目添加到数组或列表中。它可以让我根据需要添加任意数量的项目,最后我只需一键将它们插入数据库。

我在课堂上学习了 jQuery,但学不到很多东西。由于它是客户端脚本语言,因此我猜这件事只能通过这个来实现。

有人可以帮忙吗? 谢谢你:)

【问题讨论】:

  • 可以添加你的js脚本吗?
  • 我能想到的只有
  • $(document).click(function(){});
  • &lt;input type="button" name="add" class = "add" id = "&lt;?php echo $row['id'] ?&gt;" /&gt;(适用于所有按钮)。然后在你的 jquery $(document).ready(function(){$('.add').click(function(e){ e.preventDefault();var id_data = []; id_data.push($(this).attr('id'));});});
  • 应该可以,可以告诉我如何检查项目或显示该数组吗?我猜每次点击都会发出警报?

标签: javascript php jquery arrays


【解决方案1】:

检查我的示例。运行 sn-p 进行测试。每次单击添加按钮时,您都会获得 id 数组。然后你可以添加另一个按钮来提交,并且在该按钮的点击事件上你可以使用数组作为数据对你的 php 文件进行 ajax 调用。

$(document).ready(function(){
  var array_ids = [];
  $('.add_button').click(function(){
    array_ids.push($(this).parent().siblings('.row_id').html().trim());
    alert(array_ids);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
    <tr>
      <td class="row_id">1</td>
      <td>one</td>
      <td><button class="add_button">Add</button></td>
    </tr>
  <tr>
      <td class="row_id">2</td>
      <td>two</td>
      <td><button class="add_button">Add</button></td>
    </tr>
    <tr>
      <td class="row_id">3</td>
      <td>three</td>
      <td><button class="add_button">Add</button></td>
    </tr>
  <tr>
      <td class="row_id">4</td>
      <td>four</td>
      <td><button class="add_button">Add</button></td>
    </tr>
</table>

【讨论】:

  • 代码似乎可以正常工作,但是我遇到了一个垃圾,例如 12/td>,13/td>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 2016-08-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多