为什么$('#table> tr')选择器不匹配? (总是返回0) [英] Why does $('#table > tr') selector not match? (always return 0)

查看:181
本文介绍了为什么$('#table> tr')选择器不匹配? (总是返回0)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

html代码:

<table id='table'>
    <tr>
        <td>..</td>
    </tr>
</table>

带有jquery的js代码:

The js code with jquery:

var l1 = $('#table > tr').length;
var l2 = $('#table tr').length;
alert(l1+','+l2);​

结果:

 0,1

为什么第一个#table > tr变为0?

您可以从此处观看实时演示: http://jsfiddle.net/Freewind/PmsFQ/

You can see a live demo from here: http://jsfiddle.net/Freewind/PmsFQ/

推荐答案

因为<table>的直接子代只能是<thead><tbody><tfoot>(或<colgroup><caption> ,但其中不包含行.

Because the direct children of a <table> can only be <thead>, <tbody>, or <tfoot> (or <colgroup> or <caption>, but those don't contain rows).

浏览器的DOM会将杂散的<tr>隐式包装在<tbody>中. (对于不执行此操作的浏览器,jQuery会伪造它)

The browser's DOM will implicitly wrap stray <tr>s in a <tbody>. (for browsers that don't do this, jQuery fakes it instead)

您需要写$('#table > tbody > tr').

这篇关于为什么$('#table&gt; tr')选择器不匹配? (总是返回0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆