使用jQuery和一些输入创建一个键/对对象

Creating a key/pair object using jQuery and some inputs

本文关键字:一个 对象 jQuery 输入 创建 使用      更新时间:2023-09-26

我的网站上有一个购物车,我需要让用户随时轻松更改购物车中的商品数量。

以下是我迄今为止拥有的javascript代码:

<script type="text/javascript" language="javascript">
    $(document).ready(function () {
        var items = [];
        $(".item").each(function () {
            var productKey = $(this).find("input[type='hidden']").val();
            var productQuantity = $(this).find("input[type='text']").val();
            items.addKey(productKey, productQuantity); ?
        });
        // 1. Grab the values of each ammount input and it's productId.
        // 2. Send this dictionary of key pairs to a JSON action method.
        // 3. If results are OK, reload this page.
    });
</script>

我写的评论只是指导我如何继续。

有没有办法将键/对元素添加到排序数组中?我只需要它有一个关键和价值。没什么新奇的。

我在addKey()方法中写作只是为了说明目的,以展示我想要实现的目标。

items[productKey] = productQuantity;

在JavaScript中,数组是对象(typeof(new Array)==='object'),对象可以具有可以使用点或括号语法获取/设置的属性:

var a = [1,2,3];
JSON.stringify(a); // => "[1,2,3]"
a.foo = 'Foo';
a.foo; // => 'Foo'
a['foo']; // => 'Foo'
JSON.stringify(a); // => "[1,2,3]"

因此,在您的情况下,您可以简单地将productQuantity值添加到item数组的productKey属性中,如下所示:

items[productKey] = productQuantity;
items[productKey]; // => productQuantity

您可以将匿名对象添加到items数组中,例如:

items.push({
    key: productKey,
    quantity: productQuantity
});

然后稍后以items[0].keyitems[0].quantity的形式访问它们。

您还可以使用JQuery.data方法,这样您也可以消除那些隐藏的方法。