简体   繁体   English

使用jQuery选择器基于if语句存储变量

[英]Store variable based on if statement with jQuery selectors

I'm new to both Javascript and the framework jQuery. 我是Javascript和框架jQuery的新手。

Basically I'm trying to say that if the quantity is greater than 1 then don't charge a fee. 基本上我想说,如果数量大于1,那么不收取费用。 However if it is equal to 1 charge a fee. 但是,如果它等于1收费。 But I don't know how to store the variables while using jQuery. 但我不知道如何在使用jQuery时存储变量。

My thought was... (is this correct?) 我的想法是......(这是正确的吗?)

var qty = $(".qty_item");
var price = $(".price_item");
var fee = "";

if (qyt==1) {
    var fee = 250;
}

else {
    var fee = 0;
}

I've noticed though that in some jQuery plugins they declare variables like so... 我注意到,在一些jQuery插件中,他们声明变量就像这样......

qty: $(".qty_item"),
price: $(".price_item")

Any help is much appreciated. 任何帮助深表感谢。

To get values from elements, you need to use the $.val() method (assuming it's an input element). 要从元素中获取值,需要使用$.val()方法(假设它是一个输入元素)。

var price = $(".element").val();

So price would be 5 assuming the following HTML: 假设以下HTML,价格将为5:

<input type="text" value="5" class="element" />

You could simplify your fee-finding logic by using a ternary operator too: 您也可以通过使用三元运算符来简化您的费用寻找逻辑:

var fee = ($(".element").val() > 1) ? 250 : 0 ;

So if the value of our input (having the classname 'element') is greater than 1, fee will be 250. Else, fee will be the value of our input (having the id 'price'). 因此,如果我们输入的值(具有类名'元素')大于1,则费用将为250.否则,费用将是我们输入的值(具有id'价格')。

Jquery is library of javascript, you can create variables like you do in javascript: Jquery是javascript库,你可以像在javascript中一样创建变量:

var qty = $('.element').val();
var price = $('.element').val();
var fee = "";

if (qyt >= 1) {
    var fee = 250;
}
else
{
  var fee = $('#price').val();
}

Notice that i have changed the == to >= because you want to charge if quantity is greater than or equal to 1. 请注意,我已将==更改为>=因为您希望在数量大于或等于1时收费。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM