如何使用jquery获取单击按钮的特定值

问题描述 投票:-1回答:2

我有关于获取特定表行的值的问题,当我单击第一个按钮时,他们获得所有值。但是当我点击第二个按钮本身的值显示

目标:我想获得特定表行的价格值。

Output

我这里有我的Click功能

$("button.removeorderWithCondi").on("click", function() {


     var parent = $(this).closest(".condimentParent");
     var get_parent_price  = $(this).closest("tr").find(".total").text();

     console.log(get_parent_price);


});

问题:

Output problem

jquery html
2个回答
1
投票

可能更好的选择是将值与按钮强烈关联,而不是依赖可能会或可能不会更改的HTML结构。你可以使用data attribute。这样做的另一个好处是,如果格式化显示值,则可以使用原始值。

您将拥有以下内容:

$("button.removeorderWithCondi").on("click", function() {
     var price  = $(this).data("value");
     console.log(price);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<button class="removeorderWithCondi" data-value="5.00">Delete</button>

这种方法的缺点是你必须首先重构生成表的内容


0
投票

我假设你的html表将在这个结构中,希望这解决了你的问题,谢谢

$('.getprice').click(function(e){
console.log($(this).parent().prev().text())
})
td
{
border:1px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<th>Price</th>
<th>Action</th>
</tr>
<tr>
<td>20</td>
<td><button class="getprice">Click</button></td>
</tr>
<tr>
<td>0.00</td>
<td></td>
</tr>
<tr>
<td>0.00</td>
<td></td>
</tr>
<tr>
<td>50</td>
<td><button class="getprice">Click</button></td>
</tr>

</tbody>

</table>
© www.soinside.com 2019 - 2024. All rights reserved.