【问题标题】:How to use a CSS selector on a javascript list?如何在 javascript 列表中使用 CSS 选择器?
【发布时间】:2016-08-08 19:04:51
【问题描述】:

为什么这不起作用?

var animals = ['Cat', 'Dog'].valueOf;

if ("animals:contains(Cat)") {
    // ...
}

【问题讨论】:

  • javascript 对 css 一无所知。您需要使用 javascript 函数,而不是 css 选择器。
  • 您使用的是什么 HTML,您希望得到什么结果?至于你的if,看起来你想使用if (animals.indexOf('cat') > -1),使用Array.prototype.indexOf()。但是,它不起作用的原因是因为这不是您使用 JavaScript 的方式。

标签: javascript contains


【解决方案1】:

你想使用indexOf method of Array:

if(animals.indexOf('Cat') != -1){
    // ...
}

任何不为空的字符串 ("") 都将是 truthy,因此如果您使用 if("some string")if 的主体将始终运行。

【讨论】:

    【解决方案2】:

    您不能在 Javascript 中的数组上使用 CSS 选择器。您可以使用indexOf 查看数组中是否存在特定字符串。

    if (animals.indexOf('Cat') > -1) {
      console.log('We have kitties.')
    }
    

    在 Javascript 中真正使用 CSS 选择器的唯一一次是在查询 DOM 时。

    【讨论】:

      【解决方案3】:

      您似乎想要JSONSelect

      JSONSelect 定义了一种在语法和结构上非常相似的语言 CSS3 选择器。 JSONSelect 表达式是模式,可以 与 JSON 文档匹配。

      请注意,:contains 不是标准 CSS 伪类,但 JSONSelect 将其作为扩展提供。

      var animals = ['Cat', 'Dog'];
      if (JSONSelect.match(':contains("Cat")', animals).length) // truthy
        document.write('There is a cat');
      if (JSONSelect.match(':contains("Elephant")', animals).length) // falsy
        document.write('There is an elephant');
      <script src="http://jsonselect.org/js/jsonselect.js"></script>

      当然,这太过分了。 How do I check if an array includes an object in JavaScript? 中解释了更好的使用方法。

      【讨论】:

      • 这样的。换句话说,我需要的是:如果这包含另一个元素的更改 CSS
      猜你喜欢
      • 2013-08-12
      • 2014-07-31
      • 1970-01-01
      • 2012-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多