简体   繁体   English

单击行中的按钮时获取HTML TR的元素

[英]Get elements of HTML TR when a button in the row is clicked

I have the following Dynamic HTML row. 我有以下动态 HTML行。

<tr role="row" class="odd">
     <td contenteditable="false" class="sorting_1"> </td>
     <td contenteditable="false"> <span class="name">Alex Nilson </span></td>
     <td contenteditable="false"><span class="price"> 1234 </span></td>
     <td contenteditable="false"> <span class="qty" >1234 </span></td>
     <td><button class="pr_edit" href="javascript:;"> Edit </button></td>
     <td><button class="pr_elete" href="javascript:;"> Delete </button></td>
</tr>

When the edit button is clicked, I need to get the values of the cell elements of that particular row into jQuery, as JS variables, that I can AJAX POST to another PHP page to insert into database. 当单击编辑按钮时,我需要将该特定行的单元格元素的值作为JS变量导入jQuery,以便我可以AJAX POST到另一个PHP页面以插入数据库。 I tried to do it like the following, but it didn't pan out. 我尝试按照以下方式进行操作,但没有成功。

$(document).ready(function () {
     $('.pr_edit').click(function () {
         var currentTD = $(this).parents('tr').find('td');            
         $.each(currentTD, function () {
             var iname = $(this).find("span.name").html();
             var iprice = $(this).find("span.price").val();
             var iqty=$(this).find("span.qty").val();
         });

It doesn't catch the variables as I intended.How do I achieve this? 它没有捕获我想要的变量。如何实现? I need to get these SPAN data to three variables. 我需要将这些SPAN数据转换为三个变量。

You need event delegation for dynamically generated elements and use text() instead of val() to get the content of span . 您需要对动态生成的元素进行事件委托 ,并使用text()而不是val()来获取span的内容。 Also use closest('tr') to get parent tr , you don't need to use each. 还可以使用closest('tr')来获取父级tr ,而无需使用每个父级。

$(document).ready(function () {
     $('body').on('click', '.pr_edit', function () {
         var currentTR = $(this).closest('tr');
         var iname = currentTR.find("span.name").text();
         var iprice = currentTR.find("span.price").text();
         var iqty = currentTR.find("span.qty").text();
     });
 });      

If you want to work with dynamic data and jQuery, you need to bind your click-event dynamically to. 如果要使用动态数据和jQuery,则需要动态绑定点击事件。 instead : 相反:

$('.pr_edit').click(function () {
    //magic
}

do

$('.pr_edit').on('click', function () {
    //magic
}

but if even your whole table is being loaded dynamically, you have to have an element thats "allways" there as a reference. 但是,即使整个表都是动态加载的,也必须在该位置“始终”放置一个元素作为参考。 like: 喜欢:

$('html, body').on('click', '.pr_edit', function () {
  //magic
}

Check this out for refference: http://api.jquery.com/on/ 查看此内容以供参考: http ://api.jquery.com/on/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM