Javascript 具有输入字段为空的按钮未运行功能

Javascript 具有输入字段为空的按钮未运行功能,javascript,jquery,html,Javascript,Jquery,Html,因此,我有一个按钮,每当单击时,它都会在输入字段下方追加用户输入的内容。我希望在单击空字段时不会附加任何内容(基本上函数不运行) 这是我的密码: var ingrCount = 0 $("#addIngrButton").on('click', function() { var ingredientInput = $("#ingredients").val().trim(); var ingredientSpace = $("<p>"); ingredientSpace.attr(

因此,我有一个按钮,每当单击时,它都会在输入字段下方追加用户输入的内容。我希望在单击空字段时不会附加任何内容(基本上函数不运行)

这是我的密码:

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 === "") {

}
});
var ingrCount=0
$(“#添加按钮”)。在('单击',函数()上{
var ingredientInput=$(“#配料”).val().trim();
var ingredientSpace=$(“”);
属性(“id”,“成分-”+ingrCount);
追加(“+ingredientInput”);
var ingrClose=$(“”);
ingrClose.attr(“数据输入”,ingrCount);
ingrClose.addClass(“删除框”);
ingrClose.append(“✖︎");
//将按钮附加到待办事项
ingredientSpace=ingredientSpace.prepend(ingrClose);
//将按钮和配料添加到div中
$(“#listOfIngr”).append(IngreditSpace);
//完成后清除文本框
$(“#配料”).val(“”);
//添加到配料表中
ingrCount++;
如果(IngRadientInput==“”){
}
});
因此,我想创建一个if语句,说明当输入为空时,函数将不运行。但我想我可能需要将其从单击函数中移出。对于if语句,我添加了一个禁用的属性,然后在输入框包含某些内容时将其删除。但这会使按钮变为另一种颜色,而不是函数我想要。任何我可以测试的想法都会有帮助。如果您需要更多信息,请询问。

只需使用:

$("#addIngrButton").on('click', function() {
    var ingredientInput = $("#ingredients").val().trim();
    if (ingredientInput.length == 0) {
        return false;
    }
    // ..... your code
只需使用:

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

如果正在测试IngRadientInput是否为空,是否可以从click事件中返回

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

如果正在测试IngRadientInput是否为空,是否可以从click事件中返回

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

成功了!我刚刚决定在函数的操作周围包装一条if语句,使其仅在有输入时激活!我刚刚决定在函数的操作周围包装一条if语句,使其仅在有输入时激活