![]() |
Firefox 下 innerHTML 的一个 BUG |
在项目中碰到一个 BUG,代码具体如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>Firefox下innerHTML的一个BUG</title> <style type="text/css"> a { display: block; border: 1px solid red;} div { display: inline; border: 1px solid red;} </style> </head> <body> <a href="javascript:change();">change<div id="count">20</div>aaa</a> <script type="text/javascript"> function change() { var count = document.getElementById('count'); var c = count.innerHTML; var page = parseInt(c)+1; count.innerHTML = page; alert(page); } </script> </body> </html> 当你在 Firefox2.0+ 或 Firefox3.0+ 中点击链接后,会发现 innerHTML 插入的内容为<a>21</a>,而其他浏览器测试(IE6、IE7、Safari3.0+、Opera9.0+)都正常,插入内容均为文字 21。 估计是 Firefox 的一个 BUG,查找了官方网站的 BUG库,果真找到别人提交的该类问题——《Setting innerHTML on a block element inside an inline element creates extra copies of the inline element》(Bug 381808)。 我们可以参阅下8楼的 Boris Zbarsky 给出的个人解释: There are two separate concepts of block vs inline. One in CSS and one in HTML. They don’t match. In any case, the point is that in HTML <b> is not allowed to contain <div> (so the <b> needs to get closed), but the text needs to be bold for compat so we do residual style handling. HTML5 is going to define a different method of doing this anyway, so at that point we’ll need to revisit this bug. 虽然这是一个 BUG,但 BUG 的造成也却是人为的不良习惯造成的,在 WEB 标准中严格来说内联元素是不允许包含块级元素的(扩展阅读:《Allowed nesting of elements in HTML 4 Strict (and XHTML 1.0 Strict)》)。 |