为什么CSS选择器'table tr:not(tr:nth-​​child(even))'抛出TypeError? [英] Why is CSS selector 'table tr:not(tr:nth-child(even))' throwing a TypeError?

查看:290
本文介绍了为什么CSS选择器'table tr:not(tr:nth-​​child(even))'抛出TypeError?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此选择器为何起作用:

document.querySelectorAll('table tr:not(:nth-child(even))');

此选择器没有(引发TypeError):

While this selector does not (throws a TypeError):

document.querySelectorAll('table tr:not(tr:nth-child(even))');

var query = (selector) => {
  return document.querySelectorAll(selector);
};
  
try {
  var select_a = 'table tr:not(:nth-child(even))';
  var select_b = 'table tr:not(tr:nth-child(even))';

  query(select_a).forEach((node) => {
    node.style.color = 'red';
  });

  query(select_b).forEach((node) => {
    node.style.color = 'blue';
  });
} catch (e) {
    query('div:nth-child(3)')[0].textContent = e.toString();
}

var query = (selector) => {
  return document.querySelectorAll(selector);
};
  
try {
  var select_a = 'table tr:not(:nth-child(even))';
  var select_b = 'table tr:not(tr:nth-child(even))';

  query(select_a).forEach((node) => {
    node.style.color = 'red';
  });

  query(select_b).forEach((node) => {
    node.style.color = 'blue';
  });
} catch (e) {
    query('div:nth-child(3)')[0].textContent = e.toString();
}

<table>
  <tr>
    <td>row 1 first-name</td>
    <td>row 1 last-name</td>
    <td>row-1 email</td>
  </tr>
  <tr>
    <td>row 2 first-name</td>
    <td>row 2 last-name</td>
    <td>row-2 email</td>
  </tr>
  <tr>
    <td>row 3 first-name</td>
    <td>row 3 last-name</td>
    <td>row-3 email</td>
  </tr>
  <tr>
    <td>row 4 first-name</td>
    <td>row 4 last-name</td>
    <td>row-4 email</td>
  </tr>
  <tr>
    <td>row 5 first-name</td>
    <td>row 5 last-name</td>
    <td>row-5 email</td>
  </tr>
</table>

<div>Why does select_a work but not select_b?</div>

<div></div>

推荐答案

此选择器没有(引发TypeError):

While this selector does not (throws a TypeError):

document.querySelectorAll('table tr:not(tr:nth-child(even))');

:not()仅使用一个简单选择器",而tr:nth-child(even)不是一个.

:not() only takes a "simple selector", and tr:nth-child(even) isn’t one.

https://drafts.c​​sswg.org/selectors-3/#simple-selectors-dfn :

一个简单的选择器可以是类型选择器,通用选择器,属性选择器,类选择器,ID选择器或伪类.

A simple selector is either a type selector, universal selector, attribute selector, class selector, ID selector, or pseudo-class.

任一是这里的重要关键字.这些选择器类型中只有一种是允许的,而不是它们的组合.

Either is the important keyword here. Only one of those selector types is allowed, not combinations of them.

这篇关于为什么CSS选择器'table tr:not(tr:nth-​​child(even))'抛出TypeError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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