[英]Javascript - How to access tr by click a element (dynamic level) inside tr
I try to access tr when click a element inside tr. 单击tr中的元素时,我尝试访问tr。 But i don't know exactly level of the element 但是我不知道元素的确切水平
is possible to access tr if i don't know level of element? 如果我不知道元素级别,可以访问tr吗? (i want to use javascript basic) (我想使用JavaScript Basic)
Here is my example http://jsfiddle.net/mntKr/ 这是我的示例http://jsfiddle.net/mntKr/
<script>
function getTr (mythis) {
mythis.parentNode.parentNode.setAttribute('class', 'test');
// is possible to access tr if i don't know level of a tag
}
</script>
<div>
<table>
<tr>
<td>
test
</td>
<td>
<a href="#" onclick="getTr(this);">click me</a>
</td>
</tr>
<tr>
<td>
<div>
test
</div>
</td>
<td>
<div>
<a href="#" onclick="getTr(this);">click me</a>
</div>
</td>
</tr>
</table>
</div>
How to do that thanks! 怎么做,谢谢!
Absolutely. 绝对。 Keep iterating up mythis.parentNode
until you get to where mythis.nodeName == "TR"
, like so: 继续迭代mythis.parentNode
直到到达mythis.nodeName == "TR"
,如下所示:
function getTr(mythis) {
while(mythis.nodeName != "TR") mythis = mythis.parentNode;
// may want to add some additional error checking, just in case this function
// gets called by something that's not in a TR
mythis.className = "test";
}
The jQuery version, also supports dynamically added tr
's. jQuery版本还支持动态添加的tr
。
You can remove the onclick
part in your html. 您可以在HTML中删除onclick
部分。
$(function() {
$('table').on('click', 'a', function(){
e.preventDefault(); //so the browser wouldn't navigate elsewhere.
var tr = $(this).closest('tr');
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.