jQuery 创建对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11354921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:31:04  来源:igfitidea点击:

jQuery creating objects

jqueryoop

提问by Ben_hawk

How would I create an object in jQuery, and then proceed to make a couple of different instances of this object I.e

我将如何在 jQuery 中创建一个对象,然后继续创建该对象的几个不同实例,即

Create an object named box which holds a variable called color.

创建一个名为 box 的对象,其中包含一个名为 color 的变量。

And then make a couple of instances of this object with different stored colours.

然后用不同的存储颜色制作这个对象的几个实例。

回答by Luis

Another way to make objects in Javascriptusing JQuery, getting data from the domand pass it to the object Boxand, for example, store them in an array of Boxes, could be:

另一种在Javascriptusing 中创建对象的方法JQuery,从dom获取数据并将其传递给对象Box,例如,将它们存储在Boxes数组中,可能是:

var box = {}; // my object
var boxes =  []; // my array

$('div.test').each(function (index, value) {
    color = $('p', this).attr('color');
    box = {
        _color: color // being _color a property of `box`
    }
    boxes.push(box);
});

Hope it helps!

希望能帮助到你!

回答by The Alpha

May be you want this (oop in javascript)

可能你想要这个(javascript中的oop)

function box(color)
{
    this.color=color;
}

var box1=new box('red');    
var box2=new box('white');    

DEMO.

演示。

For more information.

想要查询更多的信息。

回答by Ben_hawk

I actually found a better way using the jQuery approach

我实际上找到了使用 jQuery 方法的更好方法

var box = {

config:{
 color: 'red'
},

init:function(config){
 $.extend(this.config,config);
}

};

var myBox = box.init({
 color: blue
});

回答by Control Freak

You can always make it a function

你总是可以把它变成一个函数

function writeObject(color){
    $('body').append('<div style="color:'+color+';">Hello!</div>')
}

writeObject('blue')? enter image description here

writeObject('blue')? 在此处输入图片说明