【发布时间】:2020-06-19 22:30:58
【问题描述】:
所以我尝试根据输入启用/禁用按钮,但由于某种原因我不知道为什么,它不会按照我想要的方式执行。
- 如果输入值等于或介于 1-10 之间:启用按钮。
- 如果输入值小于 1:禁用按钮。
在更改输入值的那一刻,无论值如何,按钮总是启用。如果值设置为 0,它不会被禁用。
变量inputIn 用于输入,变量inputBtn 用于按钮,因此您知道在哪里查找。
如果您发现我需要修复任何其他问题,请告诉我,因为我是 jQuery 和 Javascript 新手。
更新:
通过在 change 事件中将所有语句更改为 if 语句来解决问题。但不是最优的?
$(document).ready(function() {
let $table = $(".shoe-table");
fetch("shoes.json")
.then(resp => resp.json())
.then(data => {
let shoes = data.shoes;
let rows = [1, 2, 3];
let shoeCard = "";
let counter = 0;
rows.forEach(row => {
shoeCard += "<tr>";
for (let index = 0; index < 4; index++) {
shoeCard +=
"<td class='card text-center'>" +
"<img class='card-img-top' src=" +
shoes[counter].image +
" alt='Card image cap'>" +
"<h5 class='card-title'>" +
shoes[counter].name +
"</h5>" +
"<p class='card-text'>kr " +
shoes[counter].price +
"</p>" +
"<button id=" +
counter +
" class='orderNow btn btn-outline-dark'>ORDER NOW</button>" +
"<div id=" + counter + " class='input-form'><input class='qty-chooser' type='number' placeholder='Choose quantity' min=0 max=10>" +
"<button class='btn-add-to-cart' disabled='disabled'>ADD TO CART</button>" +
"</div>" +
"</td>";
counter++;
}
shoeCard += "</tr>";
});
$table.append(shoeCard);
let $inputForm = $(".input-form");
let $orderBtn = $(".orderNow");
$inputForm.hide();
$orderBtn.click(toggleOrder);
function toggleOrder() {
let clickedBtn = $(this);
let thisInputForm = $("#" + clickedBtn.attr("id") + ".input-form");
let inputBtn = thisInputForm.children("button");
let inputIn = thisInputForm.children("input");
function resetInputForm() {
inputBtn.css("background", "");
inputBtn.css("color", "");
inputBtn.attr("disabled", "disabled");
inputIn.val(null);
}
inputBtn.click(function() {
console.log("ADDING");
thisInputForm.hide("slow");
clickedBtn.text("ORDER NOW");
clickedBtn.css("background", "");
resetInputForm();
});
// The change function with conditions that do not work
inputIn.change(function() {
console.log("change");
let qty = inputIn.val();
if (qty >= 1 || qty <= 10) {
inputBtn.removeAttr("disabled");
inputBtn.css("background", "rgb(15, 163, 10)");
inputBtn.css("color", "white");
} else if (qty < 1) {
resetInputForm();
}
});
if (clickedBtn.text() == "CANCEL") {
thisInputForm.hide("slow");
clickedBtn.text("ORDER NOW");
clickedBtn.css("background", "");
resetInputForm();
} else {
thisInputForm.show("slow");
clickedBtn.text("CANCEL");
clickedBtn.css("background", "red");
inputBtn.attr("disabled", "disabled");
resetInputForm();
}
}
})
.catch(err => console.error(err));
});
【问题讨论】:
-
所以我尝试将更改事件中的两个条件更改为 if-statements。这显然使它以某种方式工作,即使它不是最佳解决方案。现在的问题是为什么两个单独的 if 语句有效,而 else if 语句无效
标签: javascript jquery html css conditional-statements