简体   繁体   中英

what is wrong with my code, trying to get first element text jquery?

Look at my code, I want to make it like that when a user click the table tr, I will get the first td text, so jquery I use first() and then text(), but it echo out both td 1 and td apple. I only want to get the first td text, what did I do wrong? Appreciate.

 var gridtable = $('.gridtable'); gridtable.click(function(){ var name = $(this).first().text(); alert('name'); }) 
  <tr class="gridtable"> <td>1</td> <td >apple</td> </tr> <tr class="gridtable"> <td>2</td> <td >banana</td> </tr> 

Inside handler this refers to the clicked tr applying first() method will retrieve the same tr itself . Instead, you need to filter out the nested td element. You can use the :first pseudo-class selector to get the first element.

var gridtable = $('.gridtable:first');
gridtable.click(function(){
    // get the first element within the context
    var name = $('td:first', this).text();
    alert(name);
});

 var gridtable = $('.gridtable'); gridtable.click(function() { var name = $('td:first',this).text(); alert(name); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr class="gridtable"> <td>1</td> <td>apple</td> </tr> <tr class="gridtable"> <td>2</td> <td>banana</td> </tr> </table> 

var gridtable = $('.gridtable');

gridtable.click(function(){
        var name = $(this).find('td:first').text();
        alert(name);
  });

由于要在tr级别附加点击处理程序,因此需要使用find函数选择tr内的所有tds,然后选择第一个td:

var name = $(this).find('td').first().text();

var gridtable is referring to your tr elements, so when $element.click is raised, gridtable.first() is locating the first element with class .gridtable

You could use .gridtable.children() to get the children of gridtable and use the .first() after that

Please have a look to this example: https://jsfiddle.net/gnc9t1p2/1/

Edit 1 -

As @JaromandaX said, you should use var name = $(this)... to get the clicked row.

I think below code will help out you, it's working for me.

 var gridtable = $('.gridtable');
       gridtable.click(function(){
       var name = $(this).find("td:first").text();// for only first td
                              or 
       var name =   $(this).find("td:eq(0)").text();// you can change index number like  eq(0) ,eq(1) for nect td
                alert(name);
      })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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