javascript选择当前div

时间:2016-02-02 13:35:14

标签: javascript symfony twig

我想使用jquery Click功能将所选产品的数量和价格放在另一个div标签中。 Evertime我只点击它变量" product"的第一个数组值。被展示。

如何为表格选择当前行的值。

Twig模板

<tr>
<td class="reference">{{product.reference}}</td>
<td class="product">{{product.productNr}} </td>
<td class="product">{{product.productDesp}} </td>
<td class ="price">{{product.price}}</td>
<td class="input"><input type="text" /></td>
<td class="warenkorb"><button type='submit'>in den Warenkorb</button></td>
</tr>

<div id ="cart">
<!-- Here comes the selected product by the user -->
 ????????
</div>

我的Javascript:

$('.warenkorb').click(function(){
           var reference =('.reference').text();
            alert(reference);
        });

});

数据:

 ------------------------------------------------------
| reference | product | ProductNr | quantity | price |
______________________________________________________
|Jack store| Apple    | 12435436  | 7        | 70€   |
______________________________________________________
|bill store| Apple    | 32534534  | 4        | 34€   |
______________________________________________________

2 个答案:

答案 0 :(得分:0)

您可以使用this元素。它是对单击元素的引用。 这样,您可以使用jQuery从正确的行中选择所需的值。

$('button[type=submit]').click(function(){
    var $parent = $(this).closest('tr'),
        name = $parent.find('.product-name').text(),
        quantity = $parent.find('.input input').val() || 1,
        price = $parent.find('.price').text();

   $('#cart').text(quantity + 'x ' + name  + ' - ' + price);
});

JSFiddle

答案 1 :(得分:0)

试试这个:

$('.warenkorb button').click(function() {
  	var closestTr = $(this).closest('tr');
    
    var reference = closestTr.find('.reference').html();
    var product = closestTr.find('.product').html();
    var price = closestTr.find('.price').html();
    var textdata = closestTr.find('input').val();
    
    // If you want last value to top
    $("#cart").prepend(reference+"|"+product+"|"+price+"|"+textdata);
  
     
    // If you want last value to bottom
    $("#cart").append(reference+"|"+product+"|"+price+"|"+textdata);
  
    // If you want replace div data
    $("#cart").html(reference+"|"+product+"|"+price+"|"+textdata);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table>

<tr>
  <td class="reference">a1</td>
  <td class="product">a2</td>
  <td class="price">a3</td>
  <td class="input">
    <input type="text" />
  </td>
  <td class="warenkorb">
    <button type='submit'>in den Warenkorb</button>
  </td>
</tr>

<tr>
  <td class="reference">b1</td>
  <td class="product">b2</td>
  <td class="price">b3</td>
  <td class="input">
    <input type="text" />
  </td>
  <td class="warenkorb">
    <button type='submit'>in den Warenkorb</button>
  </td>
</tr>

</table>
<div id="cart">
  <!-- Here comes the selected product by the user -->
  ????????
</div>