javascript - 来自同一类动态列表的函数

标签 javascript php jquery html

我正在处理一个项目列表,我需要在单击按钮时设置一个函数。该列表是从 php 脚本动态填充的,问题是当我单击按钮时,第一个条目可以(显示正确的信息),但其他条目显示第一个条目的信息。

<div class="col-lg-12">
<table class="table">
 <thead>
  <th>
    Nombre Local
  </th>
  <th>
    Direccion
  </th>
  <th>
    Hora de cierre
  </th>
  <th>
    Informacion
  </th>
 </thead>
 <tbody>
 <?php foreach($list as $item){
  echo '<tr>';
  echo '<td>'.$item['name'].'</td>';
  echo '<td>'.$item['addr'].'</td>';
  echo '<td>'.$item['closing'].'</td>';
  echo '<td><button class="btn btn-data detalle" data-id="'.$item['id'].'" data-tipo="'.$item['tipo'].'" onclick="GetLocalesMain()"</td>';
  echo '</tr>';
  '};?>
 </tbody>
 </table>
</div>

JS

 function GetLocalesMain(){
  var informacion =  $(".detalle");
  var id = informacion.data('id');
  var tipo = informacion.data('tipo');

  console.log(id);
  console.log(tipo);
  $.ajax({
    url: '../functions/procesa.php?item=' + id + '&tipo=' + tipo,
    type: 'POST',
    dataType: 'json',
    data: {},
    complete: function (xhr, textStatus){
    },
    success: function(data, textStatus, xhr){
     console.log('json', data);
     $(data).each(function(a){
       muestraData(this);
     });
    },
    error: function(xhr, textStatus, errorThrown) {
    }
  });
}

最佳答案

问题是您正在获取 ".detalle" 的所有实例,例如var informacion = $(".detalle");但是您需要定位单击的项目,您可以使用 jquery 非常简单地完成此操作(因为您无论如何都在使用它)。

您可以在 html 中删除 onclick="GetLocalesMain()" ,并在 javascript 中将 GetLocalesMain 函数的内容放入以下 ​​jquery click 函数中:

$( ".detalle").click(function() {
  // function contents goes here
});

然后将 var informacion = $(".detalle"); 替换为 var informacion = $(this);

您现在应该获得单击的项目以及随后的正确数据。

关于javascript - 来自同一类动态列表的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39751376/

相关文章:

javascript - 复制相同的数据请求查询,但使用 JavaScript Ajax post

javascript - 在启用按钮之前验证文本区域已填充并在表单中单击了多项选择

php - 从 Request_Uri 修剪斜杠

javascript - 使用 jQuery 动态元素

javascript - 将 Canvas DataURL 转换为图像以发布到 Facebook

php - ePub 格式的编程书籍

c# - 从 Usercontrol.ascx javascript 调用 Usercontrol.cs 中的 Webmethod

php - 在 Iframe 中丢失 SSL

php - 带有西里尔字符的 DOMPDF 问题

javascript - 有没有办法像嵌套列表一样创建表格? (图片供引用)