简体   繁体   English

jQuery $(“.class”).click(); - 多个元素,在所有元素上触发事件

[英]jQuery $(“.class”).click(); - multiple elements, event triggers on all of them

I am working on a TODO app and I am having issues with the event listeners triggering on all of the elements with the same class.我正在开发一个 TODO 应用程序,我遇到了在具有相同类的所有元素上触发的事件侦听器的问题。

Here is what I have so far:这是我到目前为止所拥有的:

  • "Add New Card" btn on page load, when the user clicks a dynamically generated list gets appended to the page.在页面加载时“添加新卡”btn,当用户单击动态生成的列表时,将附加到页面。
  • The list is wrapped in <div> , containing input and "Add" btn to dynamically add list items to the list.该列表包含在<div> ,包含 input 和“Add” btn 以将列表项动态添加到列表中。

Roadblock:路障:

  • When the user click on the "Add" btn from the dynamically generated list, it adds list items to all lists.当用户从动态生成的列表中单击“添加”btn 时,它会将列表项添加到所有列表中。

What I've tried:我试过的:

  • I found solutions for triggering the 'click' on the "Add" btn only on the e.target .我找到了仅在e.target上触发“添加”btn 上的“ 'click'解决方案。 This doesn't work in my situation as I am not clicking on the element that needs to be added, I am clicking on the button that should add the content from the input field.这在我的情况下不起作用,因为我没有点击需要添加的元素,我点击了应该从输入字段添加内容的按钮。
  • I tried this inside the function configuring the 'click' but it was unsuccessful.我在配置“点击”的功能中尝试了这个,但没有成功。
 e.stopPropagation();
 e.stopImmediatePropagation();

I have created a codepen here where you can run the existing code: https://codepen.io/skarmen/pen/qBZYZJQ我在这里创建了一个代码笔,您可以在其中运行现有代码: https ://codepen.io/skarmen/pen/qBZYZJQ

I would appreciate any guidance and help here.我很感激这里的任何指导和帮助。

Thank you!谢谢!

1 - Save the button add you clicked: 1 - 保存您单击的按钮add

const add=$(e.target);

2 - pass it into addTask function along side input 2 - 将它传递到addTask函数中的边输入

 addTask(userInput, add)

3 - Now use that button to find first list. 3 - 现在使用该按钮查找第一个列表。 So inf parent form, then immediately following sibling ol所以 inf 父表单,然后紧跟在兄弟ol

$(add).parent().next("ol").append(

4 - You are generating same ids when you generate taskCardContainer that wont work, use classes: id="to-do-list" and id="clear-btn" needs to be: class="to-do-list" and class="clear-btn" , ids needs to be unique 4 - 当您生成无法工作的taskCardContainer ,您正在生成相同的 id,使用类: id="to-do-list"id="clear-btn"需要是: class="to-do-list"class="clear-btn" , ids 需要是唯一的

 $(document).ready(function(event) { /* SUBMIT FUNCTION - listen to a click event on submit & prevent the default behaviour of the submit event - validate the userInput and add it to the list by calling (addTask f) */ function configureSubmitBehaviour() { $('.add-new-task-btn').on('click', function(e) { e.preventDefault() const add=$(e.target); const $eventTargetPreviousEl = $(e.target).prev() // e target = btn, so we are looking for the input field before the add task btn //console.log('e target:', e.target, 'this:', $(this)) //console.log('evenTargetPreviousEl:', $eventTargetPreviousEl) // store userInput in a variable let userInput = $($eventTargetPreviousEl).val().trim() //console.log('userInput:', userInput) // check if the input is valid if (userInput !== '') { addTask(userInput, add) } else { alert('Input cannot be empty. Please enter a valid task.') } }) } /* ADD NEW CARD FUNCTION */ function configureAddCardBehaviour() { $('#add-new-card-btn').on('click', function(e) { e.preventDefault() // append the task card container on btn click addCard() configureSubmitBehaviour() }) } function addCard() { let $taskCardContainer = $(` <div class="task-card-container"> <h2 class="editable"></h2> <!-- Input New Task --> <form> <label for="new-task" class="sr-only">New Task</label> <input class="new-task" type="text" placeholder="New Task" name="new-task"/> <button type="submit" class="btn add-new-task-btn">Add</button> </form> <!-- Task List --> <ol class="to-do-list" class="to-do-list sortable"> <!-- To do items added dynamically here --> </ol> <button class="clear-btn" class="btn clear-list-btn">Clear</button> </div> <!-- Task Board Container ENDS --> `) $('.main').append($taskCardContainer) //console.log('addList works') } /* ADD TASK FUNCTION - add the user input to the list - clear the input field - function is called upon submit */ function addTask(userInput, add) { let removeItem = '<button id="remove">x</button>' let checkbox = '<input type="checkbox">' // append the added element from the list $(add).parent().next("ol").append(`<li>${checkbox} <span data-id="editable-list-item">${userInput}</span> ${removeItem}</li>`); $('.new-task').val('') } configureAddCardBehaviour() })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src='https://cdnjs.cloudflare.com/ajax/libs/jeditable.js/2.0.17/jquery.jeditable.min.js'></script> <!-- jQuery UI --> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <div class="wrapper"> <div class="main"> <h2>Goals List</h2> <p><em>App description and instructions go here</em></p> <button type="submit" id="add-new-card-btn" class="btn">Add New Task Card</button> </div> <!-- Main Container ENDS --> </div> <!-- Wrapper ENDS -->

EDIT:编辑:

Just noticed.刚注意到。 You are doing something wrong from start, you have a loop somewhere.你从一开始就做错了,你在某处有一个循环。 All this functions call each other with click events inside them is messed up.所有这些函数相互调用,它们内部的点击事件都搞砸了。

Now when you have multiple cards, when adding item to list that is not the last one, it will add a list in right place but also loop all next inputs and issue an alert if empty.现在,当您有多张卡片时,将不是最后一个的项目添加到列表中时,它会在正确的位置添加一个列表,但也会循环所有下一个输入并在为空时发出警报。 Pretty sure this is not intentional.很确定这不是故意的。

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

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