我想得到按钮的父节点,它应该是td元素,但我得到了body元素。 是什么造成的? 我想只使用JavaScript,没有jQuery。
这是我的代码:
<html> <head> <meta charset="utf-8"> </head> <body> <tr> <td><input type='text'></td> <td><button class='clk' onclick="g(this)">click me!</button></td> </tr> <script src="jquery/jquery.min.js"></script> <script> function g(c) { alert(c.parentNode.nodeName); } </script> </body> </html>I want to get the parent node of the button, which should be the td element but instead I am getting the body element. What is causing that? I want to use only JavaScript, no jQuery.
This is my code:
<html> <head> <meta charset="utf-8"> </head> <body> <tr> <td><input type='text'></td> <td><button class='clk' onclick="g(this)">click me!</button></td> </tr> <script src="jquery/jquery.min.js"></script> <script> function g(c) { alert(c.parentNode.nodeName); } </script> </body> </html>最满意答案
问题是你有无效的html没有把<tr>放在<table> 。 浏览器然后拒绝它并遇到没有有效父级的<td>然后遇到没有有效父级的<button>并最终在<body> 。
当您提供无效的html标记时,会得到意外的结果。
将<tr>包装在<table></table> ,也可以在<tbody> <table></table>中的<tbody> , <thead>或<tfoot>中
请注意,某些标记,特别是表标记对于允许父和子的内容非常具体。
DEMO
The problem is that you have invalid html not putting <tr> in <table>. Browser then rejects it and encounters <td> which has no valid parent and then encounters <button> which has no valid parent and ends up in <body>.
When you provide invalid html markup you get unexpected results.
Wrap your <tr> in <table></table> and can also be in <tbody>, <thead> or <tfoot> within <table>
Note that some tags and particularly table tags are very specific about what parent and children are allowed.
DEMO
更多推荐
发布评论