简体   繁体   English

使用JavaScript连续获取第一个单元格

[英]Get first cell in a row using JavaScript

Here's the first few lines of my code: 这是我的代码的前几行:

$('tr.existing_users > td').click(function(e){

    var target_name= e.target;
    var first_element=target_name.parent.first; //wrong

e.target gives me a td which is wrapped in a tr . e.target给了我一个用tr包裹的td I want to read the innerHTML of the first element in that tr row. 我想读取tr行中第一个元素innerHTML How do I do this? 我该怎么做呢? (I'm also interested in jQuery solutions of course) (我当然也对jQuery解决方案感兴趣)

var first_element = $(this).parent().children().eq(0);
var first_html = first_element.html();
$('tr.existing_users').on("click", function(e){  //listen for click on tr
    console.log($(this).find("> td").eq(0).html());  //find children tds and get first one
});
$(e.target).closest('tr').children().first().html();

此解决方案保留现有的单击选择器,并始终为您提供第一个父tr第一个元素的html。

You can use closest() along with find() and :eq() selector: 您可以使用nearest()以及find():eq()选择器:

$('tr.existing_users > td').click(function(e){
    var first_element =  $(this).closest('tr').find(':eq(0)').html();
});

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

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