[英]Use the CSS Universal Selector '*' with javascript?
[英]How to use a CSS selector on a javascript list?
為什么這不起作用?
var animals = ['Cat', 'Dog'].valueOf;
if ("animals:contains(Cat)") {
// ...
}
您不能在 Javascript 中的數組上使用 CSS 選擇器。 您可以使用indexOf
查看數組中是否存在特定字符串。
if (animals.indexOf('Cat') > -1) {
console.log('We have kitties.')
}
在 Javascript 中真正使用 CSS 選擇器的唯一時間是在查詢 DOM 時。
看來你想要像JSONSelect這樣的東西:
JSONSelect 定義了一種在語法和結構上與 CSS3 選擇器非常相似的語言。 JSONSelect 表達式是可以與 JSON 文檔匹配的模式。
請注意:contains
不是標准的 CSS psedo 類,但 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>
但當然,這太過分了。 如何檢查數組是否包含 JavaScript 中的對象? .
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.