如果匹配,则设置数组值

时间:2016-04-27 08:53:39

标签: jquery html

我开始为一个工作项目制作一个脚本,但我想知道如何解决这个问题?如果有更好的方法呢?。

当用户调用脚本时,他可以添加一些最佳参数,如果它们存在,我希望脚本用新值替换默认值。

如下例所示,它应将Size3替换为4

$(document).ready(function () {
  $("#JGallery").JGallery({
    Size: '4'
  });
});

$.fn.JGallery = function (options) {
    var obj = {
        Size: '3',
        Width: '1190'
    };
    $.each(options, function (x, y) {
        $.each(obj, function (xx, yy) {
            if (xx == x) {
                xx = y;
            }
        });
    });
    $('#testSize').html(obj.Size)
    $('#testWidth').html(obj.Width)
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="JGallery"></div>

<div id="testSize"></div>
<div id="testWidth"></div>

我碰到了一个关于如何存在的替换价值的墙,并且很乐意以正确的方式进行指导。感谢

2 个答案:

答案 0 :(得分:1)

您需要将obj对象用作关联数组来更新它。

这是一个有效的代码:http://codepen.io/adrenalinedj/pen/qZMwVJ

以下是更正的部分:

$.each(options, function (x, y) {
    $.each(obj, function (xx, yy) {
        if (xx == x && yy != y) {
            obj[xx] = y;
        }
    });
});

我还添加了关于检查条件中的值的部分(例如yy != y)。

答案 1 :(得分:0)

最简单的解决方案是使用jQuery.extend https://api.jquery.com/jquery.extend/
在上面的例子中你可以写:
var obj = $ .extend({},{         尺寸:&#39; 3&#39;,         宽度:&#39; 1190&#39;     },options);

相关问题