2016-11-26 3 views
0

Я пытаюсь получить #id конкретной ячейки таблицы в переменной, используя jQuery, но не имея большой удачи. Может ли кто-нибудь предложить какой-нибудь совет? Я сделал скрипку here.Как настроить таргетинг на конкретную ячейку таблицы с помощью jQuery?

HTML

<input type="button" id="button" value="Click Me" /> 

<table id="myTable1"> 
    <tbody> 
    <tr> 
     <td id="1"> 
     cell 1 
     </td> 
     <td id="2"> 
     Get the id of this cell 
     </td> 
     <td id="3"> 
     cell 2 
     </td> 
    </tr> 
    </tbody> 
</table> 

JQuery

$(document).ready(function() { 
    $("#button").click(function() { 
    var td = $(this).closest('table').attr('id'); //find table id 
    alert(td); 
    }); 
}); 
+0

как следует код знать, какие ячейки ** вы ** хотите предназначаться? –

+0

Я надеюсь, что ты поможешь мне в этом. – JulianJ

+0

Используйте 'next' вместо' ближайшего', как '$ (this) .next ('table'). Attr ('id');' – Azim

ответ

1

Вот ПЕРВОЕ РЕШЕНИЕ Если вы хотите, чтобы получить все идентификаторы из каждой ячейки. Надеюсь, поможет!

$(document).ready(function() { 
 
$("#button").click(function() { 
 
    var ids = []; 
 
    $("tr > td").each(function(index){ 
 
    ids.push($(this).attr("id")); 
 
    }); 
 
    alert(ids); 
 
}); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
 
<input type="button" id="button" value="Click Me" /> 
 

 
<table id="myTable1"> 
 
    <tbody> 
 
    <tr> 
 
     <td id="1"> 
 
     cell 1 
 
     </td> 
 
     <td id="2"> 
 
     Get the id of this cell 
 
     </td> 
 
     <td id="3"> 
 
     cell 2 
 
     </td> 
 
    </tr> 
 
    </tbody> 
 
</table>

Вот ВТОРОЕ РЕШЕНИЕ, если вы хотите увидеть идентификаторами один за другим.

$(document).ready(function() { 
 
$("#button").click(function() { 
 
    $("tr > td").each(function(index){ 
 
    alert($(this).attr("id")); 
 
    }); 
 
}); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
 
<input type="button" id="button" value="Click Me" /> 
 

 
<table id="myTable1"> 
 
    <tbody> 
 
    <tr> 
 
     <td id="1"> 
 
     cell 1 
 
     </td> 
 
     <td id="2"> 
 
     Get the id of this cell 
 
     </td> 
 
     <td id="3"> 
 
     cell 2 
 
     </td> 
 
    </tr> 
 
    </tbody> 
 
</table>

Смежные вопросы