【问题标题】:jQuery select data attributes with common keywordjQuery选择具有通用关键字的数据属性
【发布时间】:2016-10-24 10:10:39
【问题描述】:

我有两个具有以下设置的元素:

<span data-placeholder-class="test-class"></span>
<span data-placeholder-template="/some/template.hbs"></span>

我使用下划线遍历包含这些属性的任何元素,然后执行相关操作(如果有)。

目前是这样完成的

_.each($('[data-placeholder-class], [data-placeholder-template]'), function cb(element) {
  // code goes here
})

与其定义要循环的每个数据属性,我想知道是否有一种方法可以选择包含公共关键字的所有属性,在本例中为占位符。例如

_.each($('[data-placeholder-*]'), function cb(element) {
  // code goes here
})

有人知道这是否可能吗?

【问题讨论】:

  • 这个问题有你要找的吗?
  • 不完全是因为它们都需要一个共同的起始选择器,例如“。滑动”。理想情况下,我想使用 data 属性作为唯一的选择器,因此我不必向任何具有这些属性的元素添加自定义类,而是可以通过属性进行选择
  • @woolm110 - Roberrrt 的问题 find 实际上更好,因为您要求的是关键字而不是开头。

标签: javascript jquery html custom-data-attribute


【解决方案1】:

您可以考虑使用一个单独的函数来创建您的选择器,这样您就不必完整地输入选择器(但您当然必须编写函数)。

e.q.:

function getSelector() {
    return Array.prototype.map.call(arguments, function(key) {
        return '[data-placeholder-' + key + ']';
    }).join(',');
}

这将返回您想要的选择器,并使用 1...N 个参数。

getSelector('class', 'template')
// returns "[data-placeholder-template],[data-placeholder-class]"

_.each($(getSelector('class', 'template')), function cb(element) {
    // code goes here
});

【讨论】:

    【解决方案2】:

    您可以迭代元素集合的attributes,如果元素.attributes.name与提供的字符串变量匹配,则将元素推送到数组中

    var spans = document.querySelectorAll("span");
    
    function filterAttrs(elems, attr, matches = []) {
      for (var elem of elems) {
        for (var attrs of elem.attributes) {
          // alternatively use `.indexOf()` or `RegExp()`
          // to match parts of string of `.name` or `.value`
          // of `.attributes` `NamedNodeMap`
          if (attrs.name.slice(0, attr.length) === attr) {
            matches.push({
              "element": elem,
              "attr": {
                "name": attrs.name,
                "value": attrs.value
              }
            })
          }
        }
      }
      return matches
    }
    
    var matches = filterAttrs(spans, "data-placeholder");
    
    console.log(matches);
    
    matches.forEach(function(match) {
      match.element.textContent = "matches:" + JSON.stringify(match.attr);
      match.element.style.color = "green";
    });
    <span data-placeholder-class="test-class"></span>
    <span data-placeholder-template="/some/template.hbs"></span>
    <span data-not-placeholder-template="/some/template.hbs">
    data-not-placeholder-template
    </span>
    <span data-not-placeholder-template="/some/template.hbs">
    data-not-placeholder-template
    </span>

    【讨论】:

      【解决方案3】:

      我知道这是一个 jquery 问题,但是由于 XPath 查询,有一种简单的方法:

      starts-with() XPath 函数正是这样做的。

      所以查询//*[@*[starts-with(name(), 'data-placeholder')]] 会告诉你你想要什么。

      解压:

       '//' + // from root to anywhere in the tree
        '*' + // any kind of node
         '[@*' + // with any attribute
            '[starts-with(name(), "data-placeholder")]' + // which starts with "data-"
                 ']'
      

      function getElementsByStartOfAttribute(start_of_attr) {
        var query = document.evaluate("//*[@*[starts-with(name(), '" + start_of_attr + "')]]",
          document, null, XPathResult.ANY_TYPE, null);
        var elements = [];
        var el;
        while (el = query.iterateNext()) {
          elements.push(el);
        }
        return elements;
      }
      
      var placehodlers = getElementsByStartOfAttribute('data-placeholder');
      console.log(placehodlers);
      $(placehodlers).css('background', 'green');
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <span data-placeholder-class="test-class">should find me</span>
      <span data-placeholder-template="/some/template.hbs">me too</span>
      <span data-not-placeholder-template="/some/template.hbs">
      data-not-placeholder-template
      </span>
      <span data-not-placeholder-template="/some/template.hbs">
      data-not-placeholder-template
      </span>

      【讨论】:

        【解决方案4】:
           var eles = $('span').filter(function() {
           for (var attrName in $(this).data()) {
             if (attrName.indexOf('placeholder') == 0) {
               return true;
             }
           }
        
           return false;
         });
        
         console.log(eles);
        

        希望对你有帮助:)

        【讨论】:

          【解决方案5】:

          示例 HTML:

          <span data-placeholder-class="test-class">test</span>
          <span data-placeholder-template="/some/template.hbs">hahaha</span>
          <span>hahahahaha</span>
          <span data-test="/some/template.hbs">hahahahaha</span>
          

          JS:

          $('span').filter(function(ndx, item){
              var data = Object.keys($(item).data())[0]; // gets data name
              if (data === undefined) {
                  return;
              }
              // checks if data starts with placeholder
              if (~(data.indexOf('placeholder'))) {
                  // do anything to that item here
                  return item;
              }
          }).css('color', 'green');
          

          小提琴:here

          希望这会有所帮助! :)

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-09-06
            • 2013-07-19
            • 2017-03-13
            • 2019-08-23
            • 1970-01-01
            • 2014-05-29
            • 2016-09-29
            • 2012-06-08
            相关资源
            最近更新 更多