[英]buttons in loop, click trigger only first button
i did a loop in which I put few buttons according to the number of colors i've got, but no matter what button i click, it shows like i click the first one, the buttons are unique, i set them id. 我做了一个循环,根据我得到的颜色数量放了几个按钮,但是无论我单击哪个按钮,它都像我单击第一个按钮一样,按钮是唯一的,我将它们设置为id。
html - loop html-循环
<td> <div> Add 2nd color </div> </td>
<td style="min-width:121px;position:relative;">
'.$pop['pop3'].'
<div id= "'.$i.'" class="btn save_img"> Choose image </div>
js: js:
$('.save_img').click(function(){
onChooseImageClick();
});
function onChooseImageClick()
{
var rowId = $('.save_img').closest('tr').attr('row_id');
alert(rowId);
the alert gives me always number 1, no matter what button i click, any points to look for the problem? 警报始终为我提供数字1,无论我单击什么按钮,是否有任何要查找问题的地方? as i tried almost everything, andi have no clue where to continue looking. 当我尝试了几乎所有东西时,我不知道在哪里继续寻找。
You need to find the closest tr
of the clicked save_img
for that you need to know which was the clicked element. 您需要找到被单击的save_img
的最接近的tr
,因为您需要知道哪个是被单击的元素。 this
inside the click handler refers to the element targeted by the handle(the save_img
element here), so pass that to onChooseImageClick
then use that element reference to find the tr
element 点击处理程序中的this
引用了handle所save_img
元素(此处的save_img
元素),因此将其传递给onChooseImageClick
然后使用该元素引用来查找tr
元素
$('.save_img').click(function () {
onChooseImageClick(this);
});
function onChooseImageClick(el) {
var rowId = $(el).closest('tr').attr('row_id');
alert(rowId);
}
$('.save_img').closest('tr')
will return all tr
elements that has a .save_img
element, then .attr('row_id')
will return the id
of the first element in that set. $('.save_img').closest('tr')
将返回所有具有.save_img
元素的tr
元素,然后.attr('row_id')
将返回该集合中第一个元素的id
。
As @John suggested below you can also use 正如@John建议的那样,您也可以使用
$('.save_img').click(onChooseImageClick);
function onChooseImageClick(el) {
var rowId = $(this).closest('tr').attr('row_id');
alert(rowId);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.