将HTML5查询选择器添加到浏览器不支持它 [英] Adding HTML5 query selector to browsers dont't support it

查看:156
本文介绍了将HTML5查询选择器添加到浏览器不支持它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 HTML5选择器API aka querySelector 。这些选择器真的很容易使用和极少。如果你不熟悉这个API,它非常类似于jQuery选择器API,他们得到一个CSS选择器字符串和选择正确的元素。例如这些选择器工作原理相同:

  jQuery('#div')== document.querySelectorAll('#div')

jQuery('。myClass a')== document.querySelectorAll('。myClass a');

这个API的浏览器支持是相当不错。 IE8支持它们。只有两个不支持此API的浏览器是IE7和IE6。我正在寻找解决方案添加这个功能到IE7和IE6。对我来说 querySelectorAll querySelector 是足够的,但如果有一个方法来实现更多的功能, p>

我开始调查 jQuery代码,他们之前做过,所以它是一个好地方看看他们如何创建选择器API,但我不明白代码。

解决方案

您可以直接使用原始

这里是Sizzle自己的描述:


一个纯JavaScript CSS选择器引擎,设计为轻松放入主机库。







如果你想确保你不使用 Sizzle if querySelectorAll 是本地支持的(即使Sizzle将总是使用 querySelectorAll ,如果可用),请使用:

  if(!document.querySelectorAll)document.querySelectorAll = Sizzle; 


I'm using HTML5 selectors API aka querySelector all the time. Those selectors are really easy to use and handful. If you're not familiar with this API it's pretty much similar to jQuery selector API they get a CSS selector string and select right elements. For example these selectors works same:

jQuery('#div') == document.querySelectorAll('#div')

jQuery('.myClass a') == document.querySelectorAll('.myClass a');

Browser support of this API is pretty good. IE8 supports them. The only two browsers that don't support this API is IE7 and IE6. I'm looking for solution to add this functionality to IE7 and IE6. For me querySelectorAll and querySelector is enough but if there was a way to implement more functions it would be great!

I started looking into jQuery code, they did it before so it would be good place to see how they created the selector API but I didn't understand the code. Any idea?

解决方案

You can simply use the original Sizzle engine which jQuery uses (written by John Resig, author of jQuery).

Here's Sizzle's own description:

A pure-JavaScript CSS selector engine designed to be easily dropped in to a host library.


If you want to be sure that you don't use Sizzle if querySelectorAll is natively supported (even though Sizzle will always use querySelectorAll when available), use this:

if ( ! document.querySelectorAll ) document.querySelectorAll = Sizzle;

这篇关于将HTML5查询选择器添加到浏览器不支持它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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