python匹配元素

    技术2022-07-11  79

    python匹配元素

    I was thinking about HTML elements and selectors recently.  We usually start by searching for an element(s) via querySelector/querySelectorAll, which makes sense, but what if you want to validate that an element that wasn't specifically selected matches a given selector?  For example, say you have a function which assumes the presence of classes or attributes on the elements it has been passed, and things might go wrong if the element provided doesn't fit the bill?  Enter Element.matches!

    我最近在考虑HTML元素和选择器。 我们通常首先通过querySelector / querySelectorAll搜索一个元素,这很有意义,但是如果您要验证未特别选择的元素与给定的选择器匹配怎么办? 例如,假设您有一个函数,它假定传递的元素上存在类或属性,并且如果提供的元素不符合要求,事情可能会出错? 输入Element.matches !

    JavaScript (The JavaScript)

    As MDN details, Element.matches is the standard API but each vendor has implemented a matchesSelector version:

    有关MDN的详细信息, Element.matches是标准API,但是每个供应商都实现了matchesSelector版本:

    function determineIfElementMatches(element, selector) { return element.matches(selector); } // Sample usage var matches = determineIfElementMatches(myDiv, 'div.someSelector[some-attribute=true]');

    To work around all of the vendor mess, we can just use the Element prototype:

    要解决所有供应商混乱的问题,我们可以使用Element原型:

    function selectorMatches(el, selector) { var p = Element.prototype; var f = p.matches || p.webkitMatchesSelector || p.mozMatchesSelector || p.msMatchesSelector || function(s) { return [].indexOf.call(document.querySelectorAll(s), this) !== -1; }; return f.call(el, selector); }

    I've included a polyfill if the browser doesn't support matches but modern browsers should support the function in some form. As I mentioned at the beginning of the post, I think `matches` is probably most used as a validation measure, but let me know if you see better uses!

    如果浏览器不支持matches则我已添加了polyfill,但现代浏览器应以某种形式支持该功能。 正如我在文章开头提到的那样,我认为“匹配”可能最常被用作一种验证手段,但是如果您看到更好的用法,请告诉我!

    翻译自: https://davidwalsh.name/element-matches-selector

    python匹配元素

    相关资源:jdk-8u281-windows-x64.exe
    Processed: 0.014, SQL: 9