即时修改元素,使其与给定的选择器匹配

时间:2015-04-03 11:30:12

标签: javascript jquery css jquery-selectors css-selectors

假设我有类似的元素:

<div class="some-class"></div>

和选择器如:

#mydiv.super.another-class[some-attribute="true"]

我想让我的div匹配这个选择器。这需要

  • 添加ID mydiv
  • 添加课程superanother-class
  • 使用值some-attribute
  • 添加属性true

所以最后的div看起来像

<div class="some-class super another-class" id="mydiv" some-attribute="true"></div>

有没有办法做类似

的事情
$(".some-class").makeMatch('#mydiv.super.another-class[some-attribute="true"]');

那将解析选择器并执行上面列出的任何有效选择器的步骤?

我知道我可以做一些解析选择器并执行它的函数,但是选择器可能非常复杂,并且选择器可能以很多不同的方式组成,我决定尝试找到一些可靠的现有解决方案。 / p>

你知道这样的事情,还是有任何本土的方式?


编辑:根据评论,我会尝试以不同的方式解释我的问题。

问题的主要问题是:

是否可以使用javascript解析任何有效的选择器,以了解它指向的id,类和属性是什么?

所以我们想要

var selectorData = parseSelector('#my-id.class-one.class-two[attr-one="value-one"]');
selectorData.id //my-id
selectorData.classes //class-one class-two
selectorData.attributes["attr-one"] //value

因为拥有关于选择器的这些数据所以很容易使任何元素匹配它。

3 个答案:

答案 0 :(得分:2)

一种可能的方法,虽然有点天真的方法,但是:

// create a jQuery plug-in, 'makeMatch()' and pass a selector
// string as an argument:
(function ($) {
    $.fn.makeMatch = function (selector) {
        // finding a string of one or more alphanumeric characters,
        // underscores and hyphens that starts with the '#' character,
        // using String.prototype.match() with a regular expression:
        var id = selector.match(/#[\w-]+/),
            // similar to the above, though this string starts with a
            // period (escaped with a back-slash because the period
            // is a special character in regular expressions), using
            // the 'g' (global) flag to retrieve all matching
            // sequences:
            classes = selector.match(/\.[\w-]+/g),
            // this string looks for strings starting with a '['
            // (again escaped because it's a special character) and
            // continuing until it matches a character that is *not*
            // ']':
            attributeValuePairs = selector.match(/\[[^\]]+/g);
        // if we have an 'id' sequence:
        if (id) {
            // assigning the found id sequence to the id variable
            // (preventing us from accessing a property of a null
            // object) after replacing the leading '#' character
            // with an empty string:
            id = id[0].replace(/^#/,'');
        }

        // iterating over the passed-in jQuery object, 'this' (here)
        // is the collection of nodes:
        return this.each(function () {
            // caching the current node found in the collection:
            var self = this;

            // if we have an id (it's not null):
            if (id) {
                // setting the id to that matched-id:
                self.id = id;
            }
            // if we have an array of classes:
            if (classes) {
                // adding the classes from the array, by joining
                // each class-string together with spaces and replacing
                // the period characters (though we could simply do:
                // classes.replace(/\./g,' ') instead):
                $(self).addClass(classes.join(' ').replace(/\./g, ''));
            }
            if (attributeValuePairs) {
                // creating a variable to avoid re-initialising a
                // variable within the forEach():
                var av;
                attributeValuePairs.forEach(function(avp) {
                    // replacing the initial '[' character from
                    // each element of the array with an empty string
                    // and splitting that string on the '=' character
                    // to form a two-part array (if a '=' character
                    // is found):
                    av = avp.replace(/^\[/, '').split('=');
                    // if we do have a two-part array:
                    if (av.length === 2) {
                      // setting the attribute held in 'av[0]' with
                      // the value held in 'av[1]' (after replacing
                      // any quotes held in that string):
                      self.setAttribute(av[0], av[1].replace(/"|'/g, ''));
                    }
                });
            }
        });
    };
})(jQuery);

(function($) {
  $.fn.makeMatch = function(selector) {
    var id = selector.match(/#[\w-]+/),
      classes = selector.match(/\.[\w-]+/g),
      attributeValuePairs = selector.match(/\[[^\]]+/g);
    if (id) {
      id = id[0].replace(/^#/,'');
    }
    return this.each(function() {
      var self = this;
      if (id) {
        self.id = id;
      }
      if (classes) {
        $(self).addClass(classes.join(' ').replace(/\./g, ''));
      }
      if (attributeValuePairs) {
        var av;
        attributeValuePairs.forEach(function(avp) {
          av = avp.replace(/^\[/, '').split('=');
          if (av.length === 2) {
            self.setAttribute(av[0], av[1].replace(/"|'/g, ''));
          }
        });
      }
    });
  };
})(jQuery);


$(".some-class").makeMatch('#mydiv.super.another-class[some-attribute="true"]');
div {
  border: 1px solid #000;
  width: 200px;
  height: 200px;
}

#mydiv.super.another-class[some-attribute="true"] {
  border: 2px solid red;
  background: transparent url(http://lorempixel.com/200/200/nightlife) 50% 50% no-repeat;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="some-class"></div>

值得注意的是,我没有解决布尔属性/属性(例如checkedselected等)的问题或者没有值添加属性的能力。这可以做到,我还没有时间来考虑这种功能可能隐含的所有边缘情况。

参考文献:

答案 1 :(得分:1)

我为你写了一个小的jquery函数

$.fn.makeMatch = function(ids, classes, attr) {
    this.attr('id', ids).addClass(classes).attr(attr);
    return this;
}

你现在只需要:

$('div').makeMatch('firstComesOneId', 'then classes seperated by space', {'data-arrayKey1' : 'value1', 'data-arrayKey2' : 'value2'})

将输出:

<div id="firstComesOneId" class="then classes seperated by space" data-arrayKey1="value1" data-arrayKey2="value2">

希望这就是你所需要的。


在op告诉我以上不是他需要它的方式之后(虽然它有效)这里是我希望他需要的功能:

    $.fn.stringToObject = function(values) {

    var selectorData = [];

    var start_posID = values.indexOf('#') + 1;
    var end_posID = values.indexOf('.',start_posID);
    selectorData['id'] = values.substring(start_posID,end_posID);


    var classSplit = values.split('.');
    var classLength = classSplit.length -1;
    var attrSplit = values.match(/\[/g);
    var attrLength = attrSplit.length;


    var start_posClass = end_posID;
    var end_posClass = values.indexOf('[',start_posClass);
    var stringClass = values.substring(start_posClass, end_posClass);
    selectorData['classes'] = stringClass.replace(/\./g, " ");

    for (var i = 0; i <= attrLength; i++) {
        if (i == 0) {
            var start = values.indexOf('[') + 1;
        } else if(i == attrLength) {
            start = nextstart -1;
        } else {
            start = nextstart +2;
        }


        var end                 = values.indexOf(']',start);
        var newstring           = values.substring(start, end);
        var nextstart           = end;

        var newstringLength     = newstring.length;
        var firstPartOffset     = newstring.indexOf('=');
        var firstPart           = newstring.substring(0, firstPartOffset);
        var secondPart          = newstring.substring(firstPartOffset +1, newstringLength);

        selectorData[firstPart] = secondPart;


    };

    return selectorData;
}

以下是您如何使用它:

var valueArray = $( "div" ).stringToObject('#mydiv.super.another-class[some-attribute1="true"][some-attribute2="truesdsda"][some-attribute3="trueasd"][some-attribute4="true"][some-attribute5="truedfg"]');

console.log(valueArray); // gives you everything
console.log(valueArray.id); // = gives you the id
console.log(valueArray.classes); // = gives you the classes
console.log(valueArray['some-attribute5']); // = gives you the value from some-attribute5

花了我一些时间,我真的希望有所帮助:)

问候timmi

答案 2 :(得分:0)

希望它能奏效。

$(".some-class").addClass('super');
$(".some-class").addClass('another-class');
$(".some-class").attr('id','myDiv');
$(".some-class").attr('some-attribute',true);