Skip to content

Commit 2504afe

Browse files
author
taoqiufeng
committed
fix: [issure10](ashi009#10)
1 parent 9d16798 commit 2504afe

File tree

1 file changed

+20
-6
lines changed

1 file changed

+20
-6
lines changed

src/index.ts

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -482,15 +482,29 @@ export class Matcher {
482482
const parts = matcher.split('.');
483483
const tagName = parts[0];
484484
const classes = parts.slice(1).sort();
485-
let source = '';
485+
let source = '"use strict";';
486486
if (tagName && tagName != '*') {
487-
if (tagName[0] == '#')
487+
let matcher: RegExpMatchArray;
488+
if (tagName[0] == '#') {
488489
source += 'if (el.id != ' + JSON.stringify(tagName.substr(1)) + ') return false;';
489-
else
490+
} else if (matcher = tagName.match(/^\[\s*(\S+)\s*(=|!=)\s*((((["'])([^\6]*)\6))|(\S*?))\]\s*/)) {
491+
const attr_key = matcher[1];
492+
let method = matcher[2];
493+
if (method !== '=' && method !== '!=') {
494+
throw new Error('Selector not supported, Expect [key${op}value].op must be =,!=');
495+
}
496+
if (method === '=') {
497+
method = '==';
498+
}
499+
const value = matcher[7] || matcher[8];
500+
source += `const attrs = el.attributes;for (const key in attrs){const val = attrs[key]; if (key == "${attr_key}" && val ${method} "${value}"){return true;}} return false;`;
501+
} else {
490502
source += 'if (el.tagName != ' + JSON.stringify(tagName) + ') return false;';
503+
}
491504
}
492-
if (classes.length > 0)
505+
if (classes.length > 0) {
493506
source += 'for (var cls = ' + JSON.stringify(classes) + ', i = 0; i < cls.length; i++) if (el.classNames.indexOf(cls[i]) === -1) return false;';
507+
}
494508
source += 'return true;';
495509
return pMatchFunctionCache[matcher] = new Function('el', source) as MatherFunction;
496510
});
@@ -537,7 +551,7 @@ export class Matcher {
537551
}
538552

539553
const kMarkupPattern = /<!--[^]*?(?=-->)-->|<(\/?)([a-z][a-z0-9]*)\s*([^>]*?)(\/?)>/ig;
540-
const kAttributePattern = /\b(id|class)\s*=\s*("([^"]+)"|'([^']+)'|(\S+))/ig;
554+
const kAttributePattern = /(^|\s)(id|class)\s*=\s*("([^"]+)"|'([^']+)'|(\S+))/ig;
541555
const kSelfClosingElements = {
542556
meta: true,
543557
img: true,
@@ -604,7 +618,7 @@ export function parse(data: string, options?: {
604618
// not </ tags
605619
var attrs = {};
606620
for (var attMatch; attMatch = kAttributePattern.exec(match[3]);)
607-
attrs[attMatch[1]] = attMatch[3] || attMatch[4] || attMatch[5];
621+
attrs[attMatch[2]] = attMatch[4] || attMatch[5] || attMatch[6];
608622
// console.log(attrs);
609623
if (!match[4] && kElementsClosedByOpening[currentParent.tagName]) {
610624
if (kElementsClosedByOpening[currentParent.tagName][match[2]]) {

0 commit comments

Comments
 (0)