简体   繁体   English

如何集体改变对象的类型?

[英]How to change objects' type in a collective way?

I have different number objects such as a = 1, b = 2. I want to use iterate method to change them into jQuery objects as followings 我有不同的数字对象,例如a = 1,b =2。我想使用迭代方法将它们更改为jQuery对象,如下所示

var a = 1, b = 2;
var ArrayToJQuery = [a, b];

for (var obj in ArrayToJQuery) {
    obj = $("<div>").text(obj);
}

a.click(function(){ alert($(this).text())}); //error

I have tried for, forin, forEach. 我已经尝试了forfor。 None of them works. 它们都不起作用。 How can I achieve that? 我该如何实现?

For this sort of thing, it's best to use object properties rather than variables: 对于这种事情,最好使用对象属性而不是变量:

var stuff = {
    a: 1,
    b: 2
};
var key;
for (key in stuff) {
    stuff[key] = $("<div>").text(stuff[key]);
}

Instead of the for-in you could use jQuery's $.each : 您可以使用jQuery的$.each代替for-in

var stuff = {
    a: 1,
    b: 2
};
$.each(stuff, function(key, entry) {
    stuff[key] = $("<div>").text(entry);
});

you can use jquery .each for this. 您可以为此使用jquery .each。

$.each([ 52, 97 ], function( index, value ) { alert( index + ": " + value );});

Please check this link for more detail with example. 请检查此链接以获取更多示例示例。

http://api.jquery.com/jQuery.each/ http://api.jquery.com/jQuery.each/

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

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