为什么我的函数中出现了错误的父节点?(Why am I getting the wrong parent node in my function?)

编程入门 行业动态 更新时间:2024-10-25 00:25:42
为什么我的函数中出现了错误的父节点?(Why am I getting the wrong parent node in my function?)

我想得到按钮的父节点,它应该是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

更多推荐

本文发布于:2023-07-04 17:24:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1027043.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:节点   函数   出现了   错误   function

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!