通过组合两个变量名称创建一个jquery变量

编程入门 行业动态 更新时间:2024-10-24 23:17:55
本文介绍了通过组合两个变量名称创建一个jquery变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我遇到了购物车的麻烦,当有人增加订购的产品数量时,该购物车会动态地将文本有货产品"更改为无货".

I'm having trouble with a shopping cart that changes the text "product in stock" with "out of stock" dynamically when someone increases the amount of ordered products.

该变量在PHP中生成,以获取产品ID作为变量名,并将库存量存储到该变量中.当我尝试在.change函数的jquery中调用该variabl时,就会出现我的问题.

The variable is generated in PHP to get the product ID as a variable name, and store the stock amount into that variable. My problem arises when I try to call that variabl in jquery in the .change function.

在这里,变量是通过使用产品ID创建的.

Here, the variable gets created by using the product ID.

<script> var stock_<?php echo $arrCartItem['intProductId']; ?> = "<?php echo $arrCartItem['intStock']; ?>"; </script>

在HTML输入字段中,数据正在发送到javascript:

in the HTML input field, the data is being send to javascript:

<td><input type="number" value="' . $arrCartItem['intQuantity'] . '" min="1" class="cartQuantity" data-cartid="'.$arrCartItem['cartId'].'" data-productid="'.$arrCartItem['intProductId'].'" /></td>

例如,当将产品2223添加到购物车时,这将创建stock_2223,并将数字8存储在其中,即库存产品的数量.

for example, this creates stock_2223 when product 2223 has been added to the shopping cart, and stores the number 8 in it, which is the amount of product in stock.

现在我正试图在.change函数中调用它:

Now i'm trying to call it in the .change function:

$('.cartQuantity').change(function(){ var curThis = $(this); var intQuantity = $(this).val(); var intCartId = $(this).data('cartid'); var intProductId = $(this).data('productid'); if (intQuantity > stock_XXXX) { // not enough in stock alert("not enough in stock"); } else { alert("enough in stock"); }

当我尝试类似的操作时:

when I try anything like:

var intProductId = "stock_"+intProductId;

导致jquery返回字符串"stock_2228",而不是包含"8"的变量.

result in jquery returning the string "stock_2228" instead of the variable which contains "8".

我的问题是,如何用购物车中的商品编号替换stock_XXXX,在这种情况下,我会得到stock_2223而无需在代码中进行实际键入,从而在jquery中给jquery编号"8" if语句.

My question is, how can I replace stock_XXXX with the number of the item in the shopping cart, in thase case, I would get stock_2223 without physically typing it in the code, and thus giving jquery the number "8" in the if statement.

是否可以通过键入变量名的第一部分stock_来创建变量名,并让第二部分由变量intProductId创建? 希望你能回答我的问题!

is it possible to create the variable name by typing the first part of the variable name, stock_, and let the second part be created by the variable intProductId? Hope you can answer my question!

推荐答案

解决方案是

window['your_dynamic_var_name'];

尝试

var stock_qty = window["stock_"+intProductId];

示例

Example

示例2: 作为操作要求

Example 2 : as op's requirement

更多推荐

通过组合两个变量名称创建一个jquery变量

本文发布于:2023-11-30 10:59:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649732.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   组合   创建一个   名称   两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!