JS自定義選擇器
阿新 • • 發佈:2018-12-26
選擇器部分:
var jojo = (function () { var jojo = function (arr) { var _this = this, i = 0; // Create array-like object for (i = 0; i < arr.length; i++) { _this[i] = arr[i]; } _this.length = arr.length; return this; }; var $ = function (selector, context) { var arr = [], i = 0; if (selector && !context) { if (selector instanceof jojo) { return selector; } } if (selector) { // String if (typeof selector === 'string') { var els, tempParent, html = selector.trim(); if (html.indexOf('<') >= 0 && html.indexOf('>') >= 0) { var toCreate = 'div'; if (html.indexOf('<li') === 0) toCreate = 'ul'; if (html.indexOf('<tr') === 0) toCreate = 'tbody'; if (html.indexOf('<td') === 0 || html.indexOf('<th') === 0) toCreate = 'tr'; if (html.indexOf('<tbody') === 0) toCreate = 'table'; if (html.indexOf('<option') === 0) toCreate = 'select'; tempParent = document.createElement(toCreate); tempParent.innerHTML = selector; for (i = 0; i < tempParent.childNodes.length; i++) { arr.push(tempParent.childNodes[i]); } } else { if (!context && selector[0] === '#' && !selector.match(/[ .<>:~]/)) { // Pure ID selector els = [document.getElementById(selector.split('#')[1])]; } else { // Other selectors els = (context || document).querySelectorAll(selector); } for (i = 0; i < els.length; i++) { if (els[i]) arr.push(els[i]); } } } // Node/element else if (selector.nodeType || selector === window || selector === document) { arr.push(selector); } else if (selector.length > 0 && selector[0].nodeType) { for (i = 0; i < selector.length; i++) { arr.push(selector[i]); } } } return new jojo(arr); }; jojo.prototype={ }; $.fn=jojo.prototype; return $; })();
測試部分:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0"> <title>自定義選擇器</title> <script type="text/javascript" src="customSelector.js"></script> <style> .item{ width:100%; height:40px; line-height:40px; text-align: center; border: 1px solid #e6e6e6; margin-top:20px; } </style> </head> <body> <div id="test1" class="item">測試文案1</div> <div class="item test2">測試文案2</div> </body> </html> <script type="text/javascript"> var t1=jojo('#test1'); var t2=jojo('.test2'); t1[0].addEventListener('click', function(){ alert(t1[0].textContent); }); t2[0].addEventListener('click', function(){ alert(t2[0].textContent); }); </script>