更改对象值jquery

时间:2015-11-04 14:40:48

标签: javascript jquery

我的jQuery中存在问题。有人可以帮我解决吗?我在jsfiddle上有我的代码:

http://jsfiddle.net/tbk5tuj9/

我的问题是,我想将image source_image_widthheight更改为其他尺寸。我的代码可以吗?

这是我的jQuery:

$(function () {
    var value = {};

    value = {
        "zoom_element": '#zoom',
        "magnifier_opacity": 1,
        "source_image_width": 200,
        "source_image_height": 200,
    };

    $(".klik").click(function () {
        console.log("Klik");
        value = {
            zoom_element: '#zoom',
            magnifier_opacity: 1,
            source_image_width: 2,
            source_image_height: 100,
        };
    });

    $('#etalage').etalage(value);

    console.log(value);
});

1 个答案:

答案 0 :(得分:1)

您的代码已成功完全替换value对象。唯一(真正的)问题是您的console.log 在<{1}}处理程序之外是 。如果您希望在点击它之后看到click,则需要将移动到您的点击处理程序中。

较小的问题是你在这里创建一个对象:

value

...然后你完全扔掉并替换在这里:

var value = {};

这些可以合并,或者只是将value = { "zoom_element": '#zoom', "magnifier_opacity": 1, "source_image_width": 200, "source_image_height": 200, }; = {}行移开。

此外,如果您只想修改您的对象,您只需指定其属性,例如:

var

仅移动value.magnifier_opacity = 1; 但仍替换整个对象的示例:

console.log
$(function() {
  var value = {};

  value = {
    "zoom_element": '#zoom',
    "magnifier_opacity": 1,
    "source_image_width": 200,
    "source_image_height": 200,
  };

  $(".klik").click(function() {
    snippet.log("Klik");
    value = {
      zoom_element: '#zoom',
      magnifier_opacity: 1,
      source_image_width: 2,
      source_image_height: 100,
    };
    snippet.log(JSON.stringify(value)); // <========= Moved and
                                        // adjusted for demo
  });

  // $('#etalage').etalage(value); Commented out for demo
});