Jquery在单击公共类时获取元素的id

时间:2016-11-03 10:40:07

标签: javascript jquery this

我以编程方式填充选项以增加和减少元素的值并将其存储在数据库表中。为了获得更好的想法,请考虑以下示例:

<tr>
  <td id="name_1">Element 1</td>
  <td><a href="#" class="increase" id="inc_1">increase icon</a></td>
  <td><a href="#" class="decrease" id="dec_1">decrease icon</a></td>
</tr>

<tr>
  <td id="name_2">Element 2</td>
  <td><a href="#" class="increase" id="inc_2">increase icon</a></td>
  <td><a href="#" class="decrease" id="dec_2">decrease icon</a></td>
</tr>

<tr>
  <td id="name_n">Element n</td>
  <td><a href="#" class="increase" id="inc_n">increase icon</a></td>
  <td><a href="#" class="decrease" id="dec_n">decrease icon</a></td>
</tr>

每当我点击n增加/减少图标中的任何一个时,我都需要访问#name_n的值。为此,我写了以下函数:

$(".increase").click(function(){
  var id = $(this).attr('id'); //get the id of the element that was clicked.
  console.log(id);

  var arr = id.split("_"); //split to get the number
  var no = arr[1]; //get the number

  var name = $("#name_"+no).text(); //get the required value in name_n
  console.log(name); 
 });
//replica for decrease class as well.

问题: 每次我点击任何增加图标时,在我的console中,我id仅为inc_1!因此,name的值始终为Element 1。使用click的{​​{1}}函数也是如此。

我尝试了以下方法来获取.decrease

id

但没有改变。同样的问题仍然存在。什么错了,我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

乍一看,您的代码看起来是正确的。也许渲染有一些问题,也许元素真的得到相同的ID。

但是,我建议使用不同的方法来完成此任务,而不使用ID。您可以通过相对于单击的增加/减少按钮引用TD元素来实现目标。我的意思是这样的。

$(".increase").click(function(){
  var $td = $(this).closest("tr").children(":eq(0)"); //get the TR's first TD

  var name = $td.text(); //get the required value in name_n td
  console.log(name); 
 });

答案 1 :(得分:1)

您可以在点击后想要触及目标的元素(当前为#name_n)添加更通用的类,并使用.closest.siblings方法。

HTML

<tr>
  <td id="name_n" class="target">Element n</td>
  <td><a href="#" class="increase" id="inc_n">increase icon</a></td>
  <td><a href="#" class="decrease" id="dec_n">decrease icon</a></td>
</tr>

JS

$(".increase").click(function(){
    var name = $(this).closest('td').siblings('.target').text();
    console.log(name);
});

这是一个有效的演示https://jsfiddle.net/0hru2jtx/