This looks like the four selection operations in the same code snippet below
$class("a").color("green");
$class("b").color("red" );
$class("c").color("green");
$class("d").color("red");
In the end, only one traversal is needed. .
Because I didn’t pay too much attention to the selector problem before. I wonder if I am out. Everyone has already thought of it?
The following is a sample, two selections and one traversal
]<script>
var $class = function () {
var checker = [];
var updateHandler = null;
var traverse = function (node,func){
func(node);
for(var i = 0; i<node.childNodes.length; i++)
{
func(node.childNodes[i])
}
}
function update () {
traverse(document.body,function(node){
for(var i = 0 ; i< checker.length; i++)
checker[i](node);
});
checker = [];
updateHandler = null;
}
function startupdate() {
if(updateHandler!==null) return ;
updateHandler = setTimeout(update,10);
}
var $class = function(jpath){
var color;
checker.push(function(node){
if(typeof node.className != "string")return;
var classes = node.className.split(" ")
for(var i = 0; i < classes.length ; i++)
if(classes[i] == jpath && color) {
node.style.backgroundColor = color;
break;
}
});
return {
color:function(v){
color = v;
startupdate();
}
}
}
$class.update = update;
return $class;
}();
$class("a").color("green");
$class("b").color("red");
</script>