Select the value of an attribute in jQuery

2019-08-29 16:15发布

问题:

I have the following table:

<table summary='' id='table_csrdownloadcenter'>
<thead>
<tr>
<th>text1</th>
<th>text2</th>      
<th>text3</th>
<th>text4</th>
<th>text5</th>
<th>text6</th>
<th>text7</th>
<th>text8</th>
</tr>
</thead>
<tbody> 

<tr id='nom_du_pdf'>
<td class='dc-date'></td>
<td class='dc-dl'></td>                                             
<td class='dc-title'></td>
<td class='dc-area'></td>
<td class='dc-category'></td>
<td class='dc-file'></td>
<td class='dc-ranking'></td>
<td class='dc-checkbox'><input type='checkbox' name='chk"+PathFile[i]+"' ></td>
</tr>

<tr id='nom_du_pdf2'>
<td class='dc-date'></td>
<td class='dc-dl'></td>                                             
<td class='dc-title'></td>
<td class='dc-area'></td>
<td class='dc-category'></td>
<td class='dc-file'></td>
<td class='dc-ranking'></td>
<td class='dc-checkbox'><input type='checkbox' name='chk"+PathFile[i]+"' ></td>
</tr>


</tbody>
<table>

For each <tr> I would like to save in a string the value of the name attribute in the 8th <td> I tried this :

function DownloadZip()
{
$('.DownloadZip').click(function(){

        var res = "";
    $('#table_csrdownloadcenter').find("tbody").find("tr").find(td:nth-child(8)).find("input").each(function(){
       res = $(this).attr("name").text();
       alert(res);
    }
});
}

Can anyone help me to make this working?

回答1:

Iterate each tr, then check the 8th td's input

var mappedAttributes = $("#table_csrdownloadcenter tr").map(function() {
    return $("td:eq(7) input", this).attr("name");
}).get();

This creates an array of each of the name attribute values.

To create a string:

var str = "";
$("#table_csrdownloadcenter tr").each(function() {
    str += $("td:eq(7) input", this).attr("name");
})


回答2:

Just remove text() method , the attr("name") will return the value of name attribute, also you are missing ""

function DownloadZip()
{
$('.DownloadZip').click(function(){    
    var res = "";
    $('#table_csrdownloadcenter').find("tbody").find("tr").find("td:nth-child(8)").find("input").each(function(){
    //                                                       ---^-----       ---^----
       res = $(this).attr("name");
       alert(res);
    }
});
}


回答3:

You can use:

res = $(this).attr("name");

instead of:

res = $(this).attr("name").text();

since $(this).attr("name") already give you the string that contain the value of your name attribute.

text() is a jQuery method and only jQuery object can utilize that method but $(this).attr("name") give you a string so obviously a string cannot apply jQuery method.

Also you're missing quotes around your selector here

find(td:nth-child(8))

It should be

find('td:nth-child(8)')


回答4:

$("td.dc-checkbox").find("input").each(function(){
  alert($(this).attr("name"));
});