在 Html Table 中是否可以获取位于另一行的元素的 id?
In Html Table is it possible to get the id of elements situated in another row?
我有这个 HTML table 结构,我在其中定义了各种行(tr):
<table>
<tr><td><button id="1" onclick="getid()"></button></td></tr>
<tr><td><button id="2" onclick="getid()"></button></td></tr>
<tr><td><button id="3" onclick="getid()"></button></td></tr>
<tr><td><button id="4" onclick="getid()"></button></td></tr>
<tr><td><button id="5" onclick="getid()"></button></td></tr>
</table>
<script>
function getid(){
alert($(this).closest('[id]'));
}
</script>
点击任何按钮,我应该能够获得位于行上方和行下方的按钮的 ID。
我没听懂。出了什么问题?
修改onclick
handler pass this
as parameter in the Html and then use .next()
and .prev()
jQuery methods 如下所示:-
HTML :-
<table>
<tr><td><button id="1" onclick="getid(this)"></button></td></tr>
<tr><td><button id="2" onclick="getid(this)"></button></td></tr>
<tr><td><button id="3" onclick="getid(this)"></button></td></tr>
<tr><td><button id="4" onclick="getid(this)"></button></td></tr>
<tr><td><button id="5" onclick="getid(this)"></button></td></tr>
</table>
jQuery :-
<script>
function getid(elem){
alert($(elem).closest('tr').prev('tr').find('button').attr('id'));
alert($(elem).closest('tr').next('tr').find('button').attr('id'));
}
</script>
我有这个 HTML table 结构,我在其中定义了各种行(tr):
<table>
<tr><td><button id="1" onclick="getid()"></button></td></tr>
<tr><td><button id="2" onclick="getid()"></button></td></tr>
<tr><td><button id="3" onclick="getid()"></button></td></tr>
<tr><td><button id="4" onclick="getid()"></button></td></tr>
<tr><td><button id="5" onclick="getid()"></button></td></tr>
</table>
<script>
function getid(){
alert($(this).closest('[id]'));
}
</script>
点击任何按钮,我应该能够获得位于行上方和行下方的按钮的 ID。
我没听懂。出了什么问题?
修改onclick
handler pass this
as parameter in the Html and then use .next()
and .prev()
jQuery methods 如下所示:-
HTML :-
<table>
<tr><td><button id="1" onclick="getid(this)"></button></td></tr>
<tr><td><button id="2" onclick="getid(this)"></button></td></tr>
<tr><td><button id="3" onclick="getid(this)"></button></td></tr>
<tr><td><button id="4" onclick="getid(this)"></button></td></tr>
<tr><td><button id="5" onclick="getid(this)"></button></td></tr>
</table>
jQuery :-
<script>
function getid(elem){
alert($(elem).closest('tr').prev('tr').find('button').attr('id'));
alert($(elem).closest('tr').next('tr').find('button').attr('id'));
}
</script>