2014-10-11 164 views
0

是否有无论如何实现以下使用纯JavaScript?jquery代码到香草javascript

if (! $('body.posts.show').length && ! $('body.posts.edit').length && ! $('body.chunks.create').length) 
{ 
    // Something here 
} 
+0

值得指出的:你的选择可能比他们应该/需要更具体。 – 2014-12-26 02:16:49

回答

3

你真的想得到一个与所有这些选择器的集合,看看它是否是空的。

在jQuery中,你可以这样做:

if (! $('body.posts.show, body.posts.edit, body.chunks.create').length) 

香草的Javascript方法并不困难得多:

if (!document.querySelector('body.posts.show, body.posts.edit, body.chunks.create')) { 

MDN documentation for document.querySelector

+0

什么是浏览器支持 – Anam 2014-10-11 07:25:33

+0

@Anam请参阅我链接的页面底部。它适用于任何版本的Chrome,FF 3.5+,IE 8+。如果你需要支持IE <8,我建议你使用一个库来帮助你。 jQuery,也许! – lonesomeday 2014-10-11 07:26:53

+0

@Anam在这里检查[浏览器支持](http://caniuse.com/#feat=queryselector) – Praveen 2014-10-11 07:27:34

1

是的!我会建议去querySelectorquerySelectorAll方法。

var body = document.querySelector('body'); 
var posts = body.querySelector('posts'); 
var chunks = body.querySelector('chunks'); 
var show = posts.querySelectorAll('show'); 
var edits = posts.querySelectorAll('edit'); 
var create = chunks..querySelectorAll('create'); 

if (!show.length && !edit.length && !create.length) { 
// Something here 
} 
1

您可以使用Javascript document.querySelectorAll('')!试试这个

if (!document.querySelectorAll('body.posts.show').length && !document.querySelectorAll('body.posts.edit').length && !document.querySelectorAll('body.chunks.create').length) 
{ 
    // Something here 
} 

更妙的是

if (!document.querySelectorAll('body.posts.show, body.posts.edit, body.chunks.create').length) 
{ 
    // Something here 
}