【问题标题】:JQuery - Event Delegation - What is happening in my code?JQuery - 事件委托 - 我的代码中发生了什么?
【发布时间】:2020-04-13 22:55:50
【问题描述】:

我已尽可能多地阅读有关事件委托的内容,但我无法弄清楚为什么我的代码会以这种方式运行。当页面加载时,所有的复选按钮都可以正常工作(在 2 个类之间切换)。每当我将新商品添加到购物清单时,检查按钮仅适用于该新商品。如果我添加第二个新项目,则检查按钮适用于该新项目,即 4 个原始项目,但不是第一个新项目。如果我添加更多项目,它将不适用于前一个项目,但适用于该项目之前的所有项目。

我怎样才能让检查按钮适用于所有项目?

HTML...

<body>

  <div class="container">
    <h1>Shopping List</h1>

    <form id="js-shopping-list-form">
      <label for="shopping-list-entry">Add an item</label>
      <input type="text" name="shopping-list-entry" id="shopping-list-entry" placeholder="e.g., broccoli">
      <button type="submit">Add item</button>
    </form>

    <ul class="shopping-list">
      <li>
        <span class="shopping-item">apples</span>
        <div class="shopping-item-controls">
          <button class="shopping-item-toggle">
            <span class="button-label">check</span>
          </button>
          <button class="shopping-item-delete">
            <span class="button-label">delete</span>
          </button>
        </div>
      </li>
      <li>
        <span class="shopping-item">oranges</span>
        <div class="shopping-item-controls">
          <button class="shopping-item-toggle">
            <span class="button-label">check</span>
          </button>
          <button class="shopping-item-delete">
            <span class="button-label">delete</span>
          </button>
        </div>
      </li>
      <li>
        <span class="shopping-item shopping-item__checked">milk</span>
        <div class="shopping-item-controls">
          <button class="shopping-item-toggle">
            <span class="button-label">check</span>
          </button>
          <button class="shopping-item-delete">
            <span class="button-label">delete</span>
          </button>
        </div>
      </li>
      <li>
        <span class="shopping-item">bread</span>
        <div class="shopping-item-controls">
          <button class="shopping-item-toggle">
            <span class="button-label">check</span>
          </button>
          <button class="shopping-item-delete">
            <span class="button-label">delete</span>
          </button>
        </div>
      </li>
    </ul>
  </div>
<script
  src="https://code.jquery.com/jquery-3.4.1.js"
  integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
  crossorigin="anonymous"></script>
<script src="script.js"></script>
</body>
</html>

CSS...

* {
    box-sizing: border-box;
  }

  body {
    font-family: 'Roboto', sans-serif;
  }

  button, input[type="text"] {
    padding: 5px;
  }

  button:hover {
    cursor: pointer;
  }

  #shopping-list-item {
    width: 250px;
  }

  .container {
    max-width: 600px;
    margin: 0 auto;
  }

  .shopping-list {
    list-style: none;
    padding-left: 0;
  }

  .shopping-list > li {
    margin-bottom: 20px;
    border: 1px solid grey;
    padding: 20px;
  }

  .shopping-item {
    display: block;
    color: grey;
    font-style: italic;
    font-size: 20px;
    margin-bottom: 15px;
  }

  .shopping-item__checked {
    text-decoration: line-through;
  }

JS...

//Make the Check Button functional
function checkButton() {
    $(".shopping-item-toggle").on("click", "span", function() {
    $(this).closest("li").find(".shopping-item").toggleClass("shopping-item__checked");
  })};
checkButton();

//Make the Delete Button functional
function delButton() {
    $(".shopping-item-delete").on("click", function() {
    $(this).parent().parent().remove();
  })};
delButton();

  //Create a variable called buttons to add the 2 buttons in function below
  let buttons = "<div class='shopping-item-controls'><button class='shopping-item-toggle'>\
                 <span class='button-label'>check</span></button>\
                 <button class='shopping-item-delete'><span class='button-label'>delete</span></button></div>";

  //Add new Item to List
  $("#js-shopping-list-form").submit(function() {
    let item = $("#shopping-list-entry").val();
    if (item != "") { //As long as the input has text in it, run the function below
    $(".shopping-list").append("<li>" + "<span class='shopping-item'>" + item + "</span>" + buttons + "</li>");
    event.preventDefault();
    checkButton();//Make the check button functional
    delButton();//Make the delete button functional
    } else { //if NO text is in the input, show this alert
      alert("Must enter an item name!");
    }
  });

【问题讨论】:

  • 请在此处包含所有相关代码作为文本。该问题应该是自包含的,并且不依赖于外部链接以便可以理解或回答 - 链接可以更改或停止工作,这意味着将来的任何访问者都无法从任何答案中受益,也不能任何人发布新答案。另外,请确保您拥有minimal reproducible example
  • @VLAZ 谢谢你。我对这一切都很陌生。我已经添加了代码。

标签: jquery event-delegation


【解决方案1】:

每当您添加新项目时,新的点击处理程序都会绑定到所有项目。这意味着页面上存在的项目可能会获得两个或多个重复的处理程序。如果两个处理程序绑定到一个项目,第一个将toggleClass 打开“已检查”类,第二个将立即关闭该类。

要使用事件委托,我建议只绑定一次处理程序,并将它们绑定到页面上始终存在的祖先。

例如:

// Bind "check" and "delete" handlers to the ".shopping-list" ancestor.

$(".shopping-list").on("click", ".shopping-item-toggle span", function() {
  $(this).closest("li").find(".shopping-item").toggleClass("shopping-item__checked");
});

$(".shopping-list").on("click", '.shopping-item-delete', function() {
  $(this).parent().parent().remove();
});


// Create a variable called buttons to add the 2 buttons in function below
let buttons = "<div class='shopping-item-controls'><button class='shopping-item-toggle'>\
                   <span class='button-label'>check</span></button>\
                   <button class='shopping-item-delete'><span class='button-label'>delete</span></button>\
               </div>";

//Add new Item to List
$("#js-shopping-list-form").submit(function(event) {
  event.preventDefault();
  let item = $("#shopping-list-entry").val();
  if (item != "") { // If the input has text in it, add the new item
    $(".shopping-list").append("<li>" + "<span class='shopping-item'>" + item + "</span>" + buttons + "</li>");
  } else { //if NO text is in the input, show this alert
    alert("Must enter an item name!");
  }
});
* {
  box-sizing: border-box;
}

body {
  font-family: 'Roboto', sans-serif;
}

button,
input[type="text"] {
  padding: 5px;
}

button:hover {
  cursor: pointer;
}

#shopping-list-item {
  width: 250px;
}

.container {
  max-width: 600px;
  margin: 0 auto;
}

.shopping-list {
  list-style: none;
  padding-left: 0;
}

.shopping-list>li {
  margin-bottom: 20px;
  border: 1px solid grey;
  padding: 20px;
}

.shopping-item {
  display: block;
  color: grey;
  font-style: italic;
  font-size: 20px;
  margin-bottom: 15px;
}

.shopping-item__checked {
  text-decoration: line-through;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="container">
  <h1>Shopping List</h1>

  <form id="js-shopping-list-form">
    <label for="shopping-list-entry">Add an item</label>
    <input type="text" name="shopping-list-entry" id="shopping-list-entry" placeholder="e.g., broccoli">
    <button type="submit">Add item</button>
  </form>

  <ul class="shopping-list">
    <li>
      <span class="shopping-item">apples</span>
      <div class="shopping-item-controls">
        <button class="shopping-item-toggle"><span class="button-label">check</span></button>
        <button class="shopping-item-delete"><span class="button-label">delete</span></button>
      </div>
    </li>
    <li>
      <span class="shopping-item">oranges</span>
      <div class="shopping-item-controls">
        <button class="shopping-item-toggle"><span class="button-label">check</span></button>
        <button class="shopping-item-delete"><span class="button-label">delete</span></button>
      </div>
    </li>
    <li>
      <span class="shopping-item shopping-item__checked">milk</span>
      <div class="shopping-item-controls">
        <button class="shopping-item-toggle"><span class="button-label">check</span></button>
        <button class="shopping-item-delete"><span class="button-label">delete</span></button>
      </div>
    </li>
    <li>
      <span class="shopping-item">bread</span>
      <div class="shopping-item-controls">
        <button class="shopping-item-toggle"><span class="button-label">check</span></button>
        <button class="shopping-item-delete"><span class="button-label">delete</span></button>
      </div>
    </li>
  </ul>
</div>

以下是添加新项目后如何触发多个处理程序的演示:

//Make the Check Button functional
function checkButton() {
  $(".shopping-item-toggle").on("click", "span", function() {
    let $item = $(this).closest("li").find(".shopping-item");
    console.log('Check Handler ' + ($item.hasClass('shopping-item__checked') ? 'OFF' : 'ON'));
    $item.toggleClass("shopping-item__checked");
  })
};
checkButton();

//Make the Delete Button functional
function delButton() {
  $(".shopping-item-delete").on("click", function() {
    console.log('Delete Handler');
    $(this).parent().parent().remove();
  })
};
delButton();

//Create a variable called buttons to add the 2 buttons in function below
let buttons = "<div class='shopping-item-controls'><button class='shopping-item-toggle'>\
                 <span class='button-label'>check</span></button>\
                 <button class='shopping-item-delete'><span class='button-label'>delete</span></button></div>";

//Add new Item to List
$("#js-shopping-list-form").submit(function(e) {
  event.preventDefault();
  let item = $("#shopping-list-entry").val();
  if (item != "") { //As long as the input has text in it, run the function below
    $(".shopping-list").append("<li>" + "<span class='shopping-item'>" + item + "</span>" + buttons + "</li>");
    checkButton(); //Make the check button functional
    delButton(); //Make the delete button functional
  } else { //if NO text is in the input, show this alert
    alert("Must enter an item name!");
  }
});
* {
  box-sizing: border-box;
}

body {
  font-family: 'Roboto', sans-serif;
}

button,
input[type="text"] {
  padding: 5px;
}

button:hover {
  cursor: pointer;
}

#shopping-list-item {
  width: 250px;
}

.container {
  max-width: 600px;
  margin: 0 auto;
}

.shopping-list {
  list-style: none;
  padding-left: 0;
}

.shopping-list>li {
  margin-bottom: 20px;
  border: 1px solid grey;
  padding: 20px;
}

.shopping-item {
  display: block;
  color: grey;
  font-style: italic;
  font-size: 20px;
  margin-bottom: 15px;
}

.shopping-item__checked {
  text-decoration: line-through;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="container">
  <h1>Shopping List</h1>

  <form id="js-shopping-list-form">
    <label for="shopping-list-entry">Add an item</label>
    <input type="text" name="shopping-list-entry" id="shopping-list-entry" placeholder="e.g., broccoli">
    <button type="submit">Add item</button>
  </form>

  <ul class="shopping-list">
    <li>
      <span class="shopping-item">apples</span>
      <div class="shopping-item-controls">
        <button class="shopping-item-toggle"><span class="button-label">check</span></button>
        <button class="shopping-item-delete"><span class="button-label">delete</span></button>
      </div>
    </li>
    <li>
      <span class="shopping-item">oranges</span>
      <div class="shopping-item-controls">
        <button class="shopping-item-toggle"><span class="button-label">check</span></button>
        <button class="shopping-item-delete"><span class="button-label">delete</span></button>
      </div>
    </li>
    <li>
      <span class="shopping-item shopping-item__checked">milk</span>
      <div class="shopping-item-controls">
        <button class="shopping-item-toggle"><span class="button-label">check</span></button>
        <button class="shopping-item-delete"><span class="button-label">delete</span></button>
      </div>
    </li>
    <li>
      <span class="shopping-item">bread</span>
      <div class="shopping-item-controls">
        <button class="shopping-item-toggle"><span class="button-label">check</span></button>
        <button class="shopping-item-delete"><span class="button-label">delete</span></button>
      </div>
    </li>
  </ul>
</div>

【讨论】:

  • 这很完美!它很好地清理了我的 JavaScript。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-18
  • 1970-01-01
  • 2013-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多