本文介绍了使用matchesSelector js检查event.target.parentElement的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不关心旧的浏览器后备。另外,不能使用库。



我有一个事件对象。我正在通过matchesSelector对css选择器测试event.target:



event ['target']。matchesSelector('css selector here') ;




$ b

event ['target'] ['parentElement']。matchesSelector('css selector here');



...和: p>

event ['target'] ['parentElement'] ['parentElement']。matchesSelector('css selector here');



我正在寻找的是一些可能的对象方法,超出我的理解,我可以用来检查每个parentElement一直在匹配,没有一个循环。我的重点是效率。



谢谢!

解决方案

通过目标元素的所有父元素进行冗余循环,您可以使用选择器使用 matchesSelector()来快速检查元素是否在与您的选择器匹配的元素内是您的原始选择器和由空格组成的附加上下文选择器和您的目标元素的标签名称的连接:

  function getAncestorBySelector(elem,selector){
if(!elem.matchesSelector(selector +''+ elem.tagName)){
//如果元素不在需要的元素内,立即返回。
返回null;
}

//循环查找与您的选择器匹配的祖先元素。
}


Not concerned about old browser fallback. Also, can't use libraries.

I have an event object. I am testing the event.target against a css selector via matchesSelector:

event['target'].matchesSelector('css selector here');

this works, as does:

event['target']['parentElement'].matchesSelector('css selector here');

...and:

event['target']['parentElement']['parentElement'].matchesSelector('css selector here');

What I'm looking for is some possible object method beyond my understanding that I could use to check each parentElement all the way up for a match, without a for loop. My focus is on efficiency.

Thanks!

解决方案

To prevent redundant looping through all parent elements of your target element, you can perform quick checking for whether your element is inside of an element that matches your selector by using matchesSelector() with selector that is concatenation of your original selector and appended context selector consisting of space and your target-element's tag name:

function getAncestorBySelector(elem, selector) {
    if (!elem.matchesSelector(selector + ' ' + elem.tagName)) {
        // If element is not inside needed element, returning immediately.
        return null;
    }

    // Loop for finding an ancestor element that matches your selector.
}

这篇关于使用matchesSelector js检查event.target.parentElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 00:07