zoukankan      html  css  js  c++  java
  • 实现兼容document.querySelector的方法

    var querySelector = function(selector) { //TODO 先简单兼容,后续继续扩展;
    	var element = null;
    	if(document.querySelector) {
    		element = document.querySelector(selector);
    	} else {
    		var selectors = selector.split(' ');
    		var context = document;
    		for(var i = 0, len = selectors.length; i < len; i++) {
    			context = handleQuery(selectors[i], context);
    		}
    		element = context;
    	}
    	return element;
    };
    var handleQuery = function(selector, context) {
    	var idSelectorRE = /^#([w-]+)$/;
    	var classSelectorRE = /^.([w-]+)$/;
    	var tagSelectorRE = /^[w-]+$/;
    	var element = null;
    	if(idSelectorRE.test(selector)) {
    		element = context.getElementById(selector.substring(1));
    	} else if(classSelectorRE.test(selector)) {
    		element = context.getElementsByClassName(selector.substring(1))[0];
    	} else if(tagSelectorRE.test(selector)) {
    		element = context.getElementsByTagName(selector)[0];
    	}
    	return element;
    };
    

    这里关键的地方,在于处理多级选择器。不过,这里没有处理同级多类型选择器的情况,后续会补充。

  • 相关阅读:
    Rocket
    Rocket
    Rocket
    Rocket
    Rocket
    Rocket
    UVa 10534 DP LIS Wavio Sequence
    LA 4256 DP Salesmen
    HDU 2476 区间DP String painter
    HDU 4283 区间DP You Are the One
  • 原文地址:https://www.cnblogs.com/xiaoyucoding/p/7611608.html
Copyright © 2011-2022 走看看