最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Replace a value in an object with jQuery - Stack Overflow

programmeradmin0浏览0评论

I would like to replace a variable in an object, but without knowing the variable's key... eg.:

var parameters = new Object();
    parameters.startregion = null;
    parameters.fx_adultnum = 2;

... bit later

$adultnum.change(function(){ setParameters("fx_adultnum", $adultnum.val() );});

and the setParameters function (what is absolutely don't work :P

function setParameters(v, value){
    console.log(parameters);
    $.each(parameters, function(key, val) {
        if (key == v) {
            console.log(key);
            console.log(val);
            $(this).val(value); // <-- not works
            }
    });
    console.log(parameters);
}

I would like to replace fx_adultnum's value to 4 for example.
Could you help in this for meh? Thanks much.

I would like to replace a variable in an object, but without knowing the variable's key... eg.:

var parameters = new Object();
    parameters.startregion = null;
    parameters.fx_adultnum = 2;

... bit later

$adultnum.change(function(){ setParameters("fx_adultnum", $adultnum.val() );});

and the setParameters function (what is absolutely don't work :P

function setParameters(v, value){
    console.log(parameters);
    $.each(parameters, function(key, val) {
        if (key == v) {
            console.log(key);
            console.log(val);
            $(this).val(value); // <-- not works
            }
    });
    console.log(parameters);
}

I would like to replace fx_adultnum's value to 4 for example.
Could you help in this for meh? Thanks much.

Share Improve this question asked Dec 4, 2011 at 18:53 RépásRépás 1,8208 gold badges28 silver badges55 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

You can access an object's property by name with a simple index:

this[val] = value; 

Just note that in $.each the this context is set to the value you're currently iterating. Did you really mean:

v[key] = val;

You might also look at jQuery's extend function

var A = { "x": 1, "y": 2 };
var B = { "y": "3", "z": 12 };

$.extend(A, B);

now A is { "x" : 1, "y": "3", "z": 12 }

Or if you want to get this same result, without modifying A, then you could do:

var newObj = $.extend({}, A, B);
发布评论

评论列表(0)

  1. 暂无评论