简体   繁体   English

如何将jQuery本机/本地范围公开给变量以扩展对象方法

[英]How to expose jQuery native / local scope to variables to extend object methods

Alright maybe this question has been answered before but I don't even really know how to ask it. 好吧,也许这个问题已经被回答过了,但是我什至不知道该怎么问。 All I can tell you what I'm trying to do. 我所能告诉你的是我要做什么。

I create an array of document objects with jQuery selector function and assign it to a variable like so: 我使用jQuery选择器函数创建文档对象数组,并将其分配给变量,如下所示:

    var imgArray = $("#rootContainer > img");

now when i iterate over the array all of the jQuery methods are gone. 现在,当我遍历数组时,所有jQuery方法都消失了。 For instance this doesn't work. 例如,这不起作用。

   for (i = 0; i < imgArray.length; i++) {
       var scaledWidth = (imgArray[i].width * 0.5); 
       imgArray[i].width(scaledWidth);
    } 

error something like width is not a function... which it's not in the standard DOM but if jQuery scope was passed to the variable it would be. 错误,例如width不是函数……这不是标准DOM中的函数,但是如果将jQuery范围传递给该变量,它将是。 I can get the code to work in pure javascript but then whats the point of abstracting away the DOM if you can't pass scope? 我可以使代码在纯JavaScript中工作,但是如果您不能通过范围,那么抽象出DOM的意义何在?

i know three ways to get needed element from array $(selector)[index] , $(selector).get(index) , $(selector).eq(index) ...and u can use foreach 我知道三种从数组$(selector)[index]$(selector).get(index)$(selector).eq(index)获取所需元素的方法...您可以使用foreach

$.foreach(imgArray,function (index, img){
     scaledWidth = (img.width() * 0.5); 
     img.width(scaledWidth);
});


for (i = 0; i < imgArray.length; i++) {
   var img = $(imgArray)[i],
       scaledWidth = (img.width() * 0.5); 
   img.width(scaledWidth);
}

When you have a jQuery instance, you can call jQuery methods. 当您拥有jQuery实例时,可以调用jQuery方法。 When you have a single DOM node, you can use the native DOM API, and call DOM methods and set DOM properties, but you cannot use jQuery methods on regular DOM elements. 如果只有一个DOM节点,则可以使用本机DOM API,并调用DOM方法并设置DOM属性,但不能在常规DOM元素上使用jQuery方法。

Here you will find more detailed information: 在这里,您会找到更多详细信息:

http://james.padolsey.com/stuff/jQueryBookThing/#dom-then-jquery http://james.padolsey.com/stuff/jQueryBookThing/#dom-then-jquery

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM