我正在处理一个项目列表,我需要在单击按钮时设置一个函数。该列表是从 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/