简体   繁体   English

我的代码有什么问题,尝试获取第一个元素文本jquery?

[英]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. 看我的代码,我想使它像这样,当用户单击表tr时,我将获得第一个td文本,因此jquery我先使用first()然后使用text(),但它会回显出td 1和td苹果。 I only want to get the first td text, what did I do wrong? 我只想获取第一个td文本,我做错了什么? 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 . 在处理程序内部, this是指单击的tr应用first()方法将检索相同的tr本身。 Instead, you need to filter out the nested td element. 相反,您需要过滤掉嵌套的td元素。 You can use the :first pseudo-class selector to get the first element. 您可以使用:first伪类选择器获取第一个元素。

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 var gridtable指的是您的tr元素,因此当提高$element.click时, gridtable.first()将使用类.gridtable定位第一个元素。

You could use .gridtable.children() to get the children of gridtable and use the .first() after that 您可以使用.gridtable.children()获取gridtable的子级,然后使用gridtable .first()

Please have a look to this example: https://jsfiddle.net/gnc9t1p2/1/ 请看以下示例: https : //jsfiddle.net/gnc9t1p2/1/

Edit 1 - 编辑1-

As @JaromandaX said, you should use var name = $(this)... to get the clicked row. 正如@JaromandaX所说,您应该使用var name = $(this)...来获得被点击的行。

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);
      })

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

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