为什么css选择器从jQuery选择器返回不同的长度

时间:2016-05-10 12:51:37

标签: jquery html jquery-selectors

我注意到这两个表达式返回不同的长度(检查控制台):



var cssSelector =  $('#target').siblings('table > tbody > tr > td').length; // returns 0
var jQuerySelector =  $('#target').siblings('table').children('tbody').children('tr').children('td').length; // returns 1
console.log('cssSelector: ' + cssSelector);
console.log('jQuerySelector: ' + jQuerySelector);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="target">Target</div>
<table>
  <tbody>
    <tr><td>Cell</td></tr>
  </tbody>
</table>
&#13;
&#13;
&#13;

我希望他们都选择相同的元素,因此他们会返回相同的结果。

3 个答案:

答案 0 :(得分:1)

.siblings('table > tbody > tr > td')匹配td个元素。你可以说,因为选择器的主题是td。由于#target的兄弟是table,而不是td,因此不会与任何内容匹配。

.siblings('table')匹配table个元素。然后,您会跟进一系列.children()次调用,这些调用会深入到表td后代,从而产生成功的匹配。

答案 1 :(得分:1)

因为table#target的兄弟,并且您说td是您var cssSelector中的兄弟姐妹,这是不正确的,因为{{1} }是td的孩子。

&#13;
&#13;
table
&#13;
var cssSelector =  $('#target').siblings('table').length; // returns 1
var jQuerySelector =  $('#target').siblings('table').children('tbody').children('tr').children('td').length; // returns 1
console.log('cssSelector: ' + cssSelector);
console.log('jQuerySelector: ' + jQuerySelector);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

此处java.lang.NullPointerException at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:636) at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:629) at org.activiti.engine.impl.persistence.entity.ExecutionEntity.take(ExecutionEntity.java:453) at org.activiti.engine.impl.persistence.entity.ExecutionEntity.take(ExecutionEntity.java:431) at org.activiti.engine.impl.bpmn.behavior.BpmnActivityBehavior.performOutgoingBehavior(BpmnActivityBehavior.java:140) at org.activiti.engine.impl.bpmn.behavior.BpmnActivityBehavior.performDefaultOutgoingBehavior(BpmnActivityBehavior.java:66) at org.activiti.engine.impl.bpmn.behavior.FlowNodeActivityBehavior.leave(FlowNodeActivityBehavior.java:44) at org.activiti.engine.impl.bpmn.behavior.AbstractBpmnActivityBehavior.leave(AbstractBpmnActivityBehavior.java:47) 提供的表格是$('#target').siblings('table')的兄弟,然后您需要通过#target

解析其子项

&#13;
&#13;
.find("tbody > tr > td")
&#13;
var cssSelector =  $('#target').siblings('table').find("tbody > tr > td").length; // returns 0
var jQuerySelector =  $('#target').siblings('table').children('tbody').children('tr').children('td').length; // returns 1
console.log(cssSelector);
console.log(jQuerySelector);
&#13;
&#13;
&#13;