简体   繁体   中英

Getting the attribute of a parent

I'm trying to get the id of a table using a table row. While I am in a loop:

$(this).parent.attr('id');

However I am getting an error. Is my syntax right?

Thanks.

EDIT:

<table id="21-rawTable" border="1"><tbody><tr class="even notSelected eClr" name="0" id="beaf-32;Developmental-Stage_Embryo-0-12h;ChIP-chip;Rep-1;input;Dmel_r54;modENCODE_21;BEAF_Input_0.CEL" title="/modencode/modencode-dcc/symbolic_links/Dmel_r5.4/Non-TF-Chromatin-binding-factor/ChIP-chip/raw-arrayfile_CEL/beaf-32/Embryo 0-12h/" style="cursor:pointer;" "="" onclick="selected('beaf-32;Developmental-Stage_Embryo-0-12h;ChIP-chip;Rep-1;input;Dmel_r54;modENCODE_21;BEAF_Input_0.CEL','[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]')"><td class="checkbox"><input type="checkbox" id="beaf-32;Developmental-Stage_Embryo-0-12h;ChIP-chip;Rep-1;input;Dmel_r54;modENCODE_21;BEAF_Input_0.CELcheckBox" checked=""></td><td>beaf-32;Developmental-Stage_Embryo-0-12h;ChIP-chip;Rep-1;input;Dmel_r54;modENCODE_21;BEAF_Input_0.CEL</td><td>0 bytes</td></tr><!-- table--></tbody></table>

Using this code to get the id of the table which in this case is "21-rawTable"

$(".selected").each(function () {
var parentname = $(this).parent().attr('id');
        alert (parentname);
});

I resolved the issue. I think it was giving me the direct parent. Instead I had to do a search for the closest ancestor like such:

var parentname = ($(this).closest('table')).attr('id');

Thanks.

parent [ API Ref ]是一种方法,因此您应该这样调用它:

$(this).parent().attr('id');

我认为您需要在对parent()函数的调用中包含括号。

I don't see any tags with class='selected' in your sample HTML. However:

  • the parent of the checkbox is the TD.
  • the parent of the TD is the TR.
  • the parent of the TR is the TBODY.
  • the parent of the TBODY is the TABLE.

You can use .closest(selector) to get the table ancestor from anywhere inside of it, though:

$(this).closest('table').attr('id');

http://api.jquery.com/closest/

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