【问题标题】:Can't select HTML5 element's children in IE8 with jQuery selector无法使用 jQuery 选择器在 IE8 中选择 HTML5 元素的子元素
【发布时间】:2010-07-28 11:54:02
【问题描述】:

我发现了一些有类似问题的帖子,但这是不同的。阅读另一篇文章后,我从 jQuery 1.4 升级到 1.4.2,但问题仍然存在。我还尝试在兼容模式下运行 IE 8,但似乎没有任何效果。当然,它在 Chrome 中运行良好。

这是标记:

<section class="pleaseWaitButton">
    <p><img src="images/please_wait.png" alt="Please wait" /></p>
    <p><input type="image" src="images/add_to_cart.png" alt="Add to cart"/></p>
</section>

这是在这种情况下起作用的唯一 jQuery 选择器...

$('.pleaseWaitButton').length // 1

这里的 jQuery 选择器不起作用!

$('.pleaseWaitButton').find('input').length // 0
$('.pleaseWaitButton input').length // 0
$('.pleaseWaitButton > p > input').length // 0

有什么想法吗?有人...?

【问题讨论】:

    标签: javascript jquery dom html internet-explorer-8


    【解决方案1】:

    Internet Explorer 8 对 HTML 5 有古怪的支持,IE6 和 IE7 普通版不支持。

    您需要shiv HTML 5 元素,以便在其上设置样式并正确使用方法/属性,例如 innerHTML、getElementsByTagName。

    这将在 IE6-IE8 中工作:

    <!doctype html> 
    <html> 
    <!--[if lt IE 9]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]--> 
    <section class="pleaseWaitButton"> 
        <p><img src="images/please_wait.png" alt="Please wait" /></p> 
            <p><input type="image" src="images/add_to_cart.png" alt="Add to cart"/></p> 
    </section> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script> 
    <script> 
        alert( $('.pleaseWaitButton').find('input').length ) 
        alert( $('.pleaseWaitButton input').length ) 
        alert( $('.pleaseWaitButton > p > input').length ) 
    </script> 
    </html> 
    

    现场演示:http://medero.org/html5.html

    【讨论】:

    • 请注意,shiv 并不能解决新元素的所有问题;特别是innerHTML 需要特别注意。我还不会使用 HTML5 语义容器元素:它们只会给你 IE 错误,而且对 div 没有什么实际好处。
    • 我会说 HTML5 元素使我的 css 与我之前编写的相比非常干净。例如,每次我为页面上的主要项目设置样式时,它始终是我的文章元素,所以 css 非常干净,因为我只需要设置文章元素的样式。这只是一个例子。大多数情况下不需要 id。
    • 感谢您的回答。到目前为止它运作良好。我从来没有使用过 interHTML,所以这不会是一个问题。
    【解决方案2】:

    &lt;section&gt; 是 IE8 不支持的 HTML5 元素,将其作为元素使用时会遇到问题,包括在其下查找子元素。不是 jQuery 问题,是基本的 DOM 问题,here's a demonstration:

    我所做的只是给元素一个 ID 来简化事情:

    <section class="pleaseWaitButton" id="btn">
    

    然后尝试得到它的孩子:

    document.getElementById('btn').children.length
    

    这会让您在 HTML5 浏览器中获得 2,在 IE 中获得 0。

    【讨论】:

    • 您可以手动创建元素,以便 IE 正确支持样式和 DOM 操作。 Jonathan Neal 还修复了打印 HTML 5 元素,因为 IE 本身不支持 HTML 5 元素。
    • @meder - 没错,我的回答是 why 不起作用,而 html5shiv 代码有 other issues,所以这不是一个快速修复。作为旁注,对于您的示例,在执行示例页面时,请确保具有有效的 HTML,否则它不是有效的测试:)
    • @sfjedi - 例如,HTML 文档需要 &lt;head&gt; :)
    • A &lt;head&gt;&lt;title&gt; 不会影响我的测试用例。与 &lt;body&gt; 元素相同。
    • 幸运的是,我们在这里可能都足够聪明,可以解决这个问题。谢谢你的例子,meder。
    猜你喜欢
    • 2023-04-09
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 2013-02-24
    • 1970-01-01
    • 2013-07-17
    • 1970-01-01
    相关资源
    最近更新 更多