因此,我有一个按钮,只要单击该按钮,便会将用户输入的任何内容追加到输入字段下方。我要这样做,以便在单击空白字段时不附加任何内容(本质上该功能无法运行)。

这是我的代码:

var ingrCount = 0

$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
var ingredientSpace = $("<p>");
ingredientSpace.attr("id", "ingredient-" + ingrCount);
ingredientSpace.append(" " + ingredientInput);

var ingrClose = $("<button>");

ingrClose.attr("data-ingr", ingrCount);
ingrClose.addClass("deleteBox");
ingrClose.append("✖︎");

// Append the button to the to do item
ingredientSpace = ingredientSpace.prepend(ingrClose);

// Add the button and ingredient to the div
$("#listOfIngr").append(ingredientSpace);

// Clear the textbox when done
$("#ingredients").val("");

// Add to the ingredient list
ingrCount++;

if (ingredientInput === "") {

}
});


因此,我想创建一个if语句,说明输入为空时该函数无法运行。我想我可能需要将其移出点击功能。对于if语句,我添加了一个禁用的属性,然后在输入框中包含某些内容时将其删除。但这会使按钮变成另一种颜色,而不是我想要的功能。我可以测试的任何想法都会有所帮助。如果您需要更多信息,请询问。

最佳答案

如果要测试IngredientInput是否为空,是否可以从click事件中返回?

$("#addIngrButton").on('click', function() {
  var ingredientInput = $("#ingredients").val().trim();
  if(ingredientInput === '') { return; }
  // rest of code

10-05 20:50
查看更多