[英]using this. in a jquery selector
In a javascript program there is an array (gData) that contains objects. 在javascript程序中,有一个包含对象的数组(gData)。
Each of these objects has a property called label that is an object. 这些对象中的每个对象都有一个称为标签的属性,它是一个对象。
each label contains a span called span_ within a div called div_. 每个标签在名为div_的div中包含一个称为span_的跨度。
Amongst other gData related operations, the label object is instantiated as 在其他与gData相关的操作中,标签对象被实例化为
gData.label = new Label();
and then the gData object is pushed onto the gData array. 然后将gData对象压入gData数组。
In the main program, i can execute the following jquery code that works fine: 在主程序中,我可以执行以下运行良好的jquery代码:
$(gData[0].label.span_).css("border","5px solid green");
I want to add a function prototype to the label object called setCSS(). 我想将函数原型添加到名为setCSS()的标签对象中。 I would call the setCSS method like this:
我将这样调用setCSS方法:
gData[0].label.setCSS("border","5px solid green");
The setCSS code that I wrote (below) does not work. 我编写的setCSS代码(如下)不起作用。 I'm guessing that the selector isn't working.
我猜选择器不起作用。
Label.prototype.setCSS = function(args) {
// args contains an object in the form {"cssAtribute":"cssData"}
// call this method as label.setCSS({"border":"3px solid blue"});
// Any number of css attributes can be included in the args object
$.each(args, function(theKey, theValue) {
$(this.span_).css(theKey, theValue);
});
}
I've tried $(this.span_), $(this.div.span_) and several other selectors, none work. 我已经尝试了$(this.span _),$(this.div.span_)和其他几个选择器,但都没有用。
Using Firebug I can see that gData[0] contains a label object and the label object contains a span_ object. 使用Firebug,我可以看到gData [0]包含一个标签对象,而标签对象包含一个span_对象。 Is my selector specification wrong?
我的选择器规格有误吗? or have I missed some other cause that will make me feel dumb?
还是错过了其他使我感到愚蠢的原因?
this
inside a jQuery.each
will have a different scope. this
在jQuery.each
中将具有不同的范围。 You need to save it first in a local variable: 您需要先将其保存在本地变量中:
var $span = $(this.span_);
$.each(args, function(theKey, theValue) {
$span.css(theKey, theValue);
});
Note that you example .setCSS("border","5px solid green");
请注意,您的示例
.setCSS("border","5px solid green");
will not work using this method, as it requires the argument to be an object using key/values. 将无法使用此方法,因为它要求参数必须是使用键/值的对象。
However, you should be able to simplify the method to: 但是,您应该能够将方法简化为:
Label.prototype.setCSS = function() {
$.prototype.css.apply($(this.span_), $.makeArray(arguments));
};
That way you can use it the same way jQuery uses .css()
including your implementation example. 这样,您就可以像jQuery使用
.css()
一样.css()
包括实现示例.css()
使用它。
Fiddles: 小提琴:
First example: http://jsfiddle.net/ESrSY 第一个示例: http : //jsfiddle.net/ESrSY
Second example: http://jsfiddle.net/UpEPK 第二个示例: http : //jsfiddle.net/UpEPK
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.