2012-01-09 184 views
0

我正在通过peepcode jQuery示例(https://peepcode.com/products/jquery),我选择更新所有依赖关系。JQuery.each将字符串文字转换为字符串。为什么?

不足为奇的是,我遇到了一个问题,关于字符串和String对象之间的JavaScript(大讨论在这里:Why are there two kinds of JavaScript strings?)的区别

一个问题我打的是jQuery.each字符串文字转换为字符串jQueryUI方法removeClass无法正确处理的对象。这是修复问题的代码片段。

我想知道如果错误是在jQuery.each错误地将字符串文字转换为字符串对象或应该removeClass假设它可以得到一个字符串文字或字符串对象。

更新:我刚刚意识到这是另一种解决办法: Strings in array are no longer strings after jQuery.each()

下面的代码:

jQuery.fn.extend({ 
    taskStates:["task-empty", "task-x", "task-apostrophe", "task-dash"], 

    resetTaskStateClassNames: function() { 
     var elements = this; 
// Commented code breaks as "this" becomes the String object not the literal 
// and removeClass does not check for String Object 
//  jQuery.each(jQuery.fn.taskStates, function(){ 
//   elements.removeClass(this); // this is the taskState 
//  }) 
     jQuery.fn.taskStates.forEach(function(ts) { 
      elements.removeClass(ts); 
     }); 
     return this; 
    }, 

回答

0

这是工作的jQuery代码片段。自从截屏制作后,我想API(http://api.jquery.com/jQuery.each/)发生了变化。

 jQuery.each(jQuery.fn.taskStates, function(index, value){ 
      elements.removeClass(value); // this is the taskState as a string literal 
     }) 

除了这个事实,你可以在任一对象的属性或数组jQuery.each,我没有看到过简单地使用JavaScript的forEach

任何优势
2

这有什么好做的jQuery。非严格模式下的this的值被强制为一个对象,就像Object(this)一样。

http://es5.github.com/#x10.4.3

10.4.3输入功能码#Ⓣ

当控制进入包含在函数对象F代表功能代码的执行上下文,提供thisArg呼叫者执行下面的步骤,和一个呼叫者提供argumentsList:

  1. 若功能码是严格代码,所述ThisBinding设定为thisArg
  2. 不然,如果thisArgnullundefined,则ThisBinding设置为全局对象。
  3. 不然,如果类型(thisArg)对象,设置ThisBinding到ToObject(thisArg)
  4. 其他设置ThisBindingthisArg