2010-08-01 4 views
2

Из моего понимания Sizzle возвращает массив объектов (DOMElements), я пытаюсь пройти этот массив объектов в цикле for, но я получаю ошибки. Когда я пытаюсь получить свойство сНевозможно перебрать массив из Sizzle

obj[index-number]["property"] 

он работает нормально, но когда я пытаюсь получить доступ к нему после прохождения его в другую функцию

obj[index-number][arguments[index-number]] 

Я получаю возврат неопределенными. Я пробовал много разных способов, в том числе eval для разбора точечной нотации безрезультатно. Я в тупике. Любые указатели или идеи были бы удивительными. Кроме того, я проверил, что все введенные функции корректны (посредством их предупреждения), а также жесткое кодирование значений, чтобы получить то, что я хочу в функции. Вот мой код: (извините, это длинный) .....

var ecmafw = function() { 
    // Creates the new instance of the object. 

    // Sets up the objects global properties: 
     this.error = false; 

    // Checks to see if arguments were supplied, if none are then it returns false. 
    if (arguments.lenght == 0) { 
     this.error = "No arguments were supplied."; 
     return false; 
    } 

    // Gives a reference to the result set. 
    this.results = Sizzle(arguments[0]); 

    this.attr = function() { 
     /* Purpose: To add/remove/update an attribute from the results set. 
     * 
     * Can be used in two ways: 
     *  1: .attr("attribute1='value' attribute2='value' attribute3='value'") // adds/removes them all. [negate value to be removed with "-" (used for class)] 
     *  2: .attr("attribute", "value") // adds the one. [negate value to be removed with "-" (used for class)] 
     *  3: .attr("attribute") // removes the one. 
     *  4: .attr("attribute1 attribute2 attribute3") // removes them all. 
     */ 

     var len = this.results.length; 
     switch (arguments.length) { 
      case 1: 
       for (var a=0; a < len; a++) { 
        var re = new RegExp("=", "g"); 
        if (re.test(arguments[0])) { 
         // Provided a list of attributes to update/create. 
         valuePairs = arguments[0].split("' "); 

         for (var i=0; i < valuePairs.length; i++) { 
          var attributeValue = valuePairs[i].split("="); 
          var newRE = new RegExp(/^-/); 
          var value = attributeValue[1].replace(/'/g, ""); 

          if (newRE.test(value)) { 
           this.removeAttr(attributeValue[0], a, value); 
          } else { 
           this.setAttr(attributeValue[0], value, a); 
          } 
         } 
        } else { 
         var attributeSplit = arguments[0].split(" "); 
         if (attributeSplit.length == 1) { 
          // Provided a single attributes to remove. 
          this.removeAttr(arguments[0], a); 
         } else { 
          // Provided multiple attributes to remove. 
          for (var i=0; i < attributeSplit.length; i++) { 
           this.removeAttr(attributeSplit[i], a); 
          } 
         } 
        } 
       } 
       break; 
      case 2: 
       // Provided a single name/value pair to update. 
       for (var a=0; a < len; a++) { 
        this.setAttr(arguments[0], arguments[1], a) 
       } 
       break; 
      default: 
       // Either 0 or more than 2 arguments were supplied. 
       this.error = "There were no arguments supplied with the attr() function, or there were too many supplied."; 
       return false 
       break; 
     } 
    }; 

    this.setAttr = function() { 
     // Counters for IE className 
     if (document.all && !window.opera) { 
      arguments[0] = arguments[0].replace(/class/gi, "className"); 
     } 
     if (arguments[0] == "class" || arguments[0] == "className") { 
      if (this.results[arguments[2]][arguments[0]] != undefined) { 
       arguments[1] += " " + this.results[arguments[2]][arguments[0]]; // Failing 
      } 
     } 
     if (this.results[arguments[2]].setAttribute) { 
      this.results[arguments[2]].setAttribute(arguments[0], arguments[1]); 
     } else { 
      this.results[arguments[2]][arguments[0]] = arguments[1]; 
     } 
    }; 

    this.removeAttr = function() { 
     arguments[0] = arguments[0].replace(/class/gi, "className"); 
     var item = this.results[arguments[1]]; 

     if (arguments[0] == "className") { 
      arguments[2] = arguments[2].replace("-", ""); 
      var replaceRE = new RegExp(arguments[2], "gi"); 

      // For some reason it would find it like this, This is fine but it is not working 
      // in Opera. Opera is failing to convert item[eachItem] to an object. (so it says in its error log) 
      for (var eachItem in item) { 
       if (arguments[0] == eachItem) { 
        item[eachItem] = item[eachItem].replace(replaceRE, " "); 
        item[eachItem] = item[eachItem].replace(/ /gi, " "); 
        item[eachItem] = item[eachItem].replace(/^ /gi, ""); 
        item[eachItem] = item[eachItem].replace(/ $/gi, ""); 
       } 
      } 
     } else { 
      if (this.results[arguments[1]].removeAttribute) { 
       this.results[arguments[1]].removeAttribute(arguments[0]); 
      } else { 
       this.results[arguments[1]][arguments[0]] = ""; 
      } 
     } 
    }; 

    // Returns a reference to itself. 
    return this; 
} 
+0

Ошибки в каком браузере? Некоторые свойства доступны только для чтения в IE, поэтому, если вы попытаетесь установить их, вы получите сообщение об ошибке в IE. – slebetman

ответ

0

Не уверен, если это может быть проблема, но в функции removeAttr вы получаете доступ к 3-й аргумент, передаваемый в этой строке:

arguments[2] = arguments[2].replace("-", ""); 

Однако в 2 из 3 вызовов этой функции вы передаете только 2 аргумента. Если приведенная выше строка работает в любом из этих случаев, arguments[2] будет undefined и вызовет replace("-", ""), на нем будет выбрасываться ошибка.

Кроме того, у вас есть опечатка в ваших начальных аргументах в верхней части: arguments.lenght.

+1

Спасибо за помощь. – John

+0

Добро пожаловать. Рад, что это сработало для вас. – Bryan

Смежные вопросы