简体   繁体   English

将事件监听器保留在列表的最后一个元素上

[英]Keep event listener on last element of list

I have an un-ordered list with mutiple li elements inside of it. 我有一个无序列表,里面有多个li元素。 The last element has an on click event listener which adds another li element to the list, seen in this fiddle. 最后一个元素具有on click事件侦听器,该事件侦听器将另一个li元素添加到列表中,如该小提琴所示。

https://jsfiddle.net/45vyLdra/ https://jsfiddle.net/45vyLdra/

What I want to do is have the on click event always be on the last element of the list, even after I have appended the new li. 我想做的是,即使在我添加了新li之后,on click事件也始终位于列表的最后一个元素上。 Is there a clean way to do this? 有没有一种干净的方法可以做到这一点? If I re-run line 2 of 如果我重新运行第2行

$( document ).ready(function() {
    $("li").last().on("click",function(){
        $("ul").append("<li><a href='#'>Button</a></li>")
    })
})

and just unbind the original event it would work but that seems easier said than done. 并取消绑定原始事件就可以了,但是说起来容易做起来难。

The problem you have is that you can't attach an event-handler to an element that doesn't yet exist in the DOM on page load. 您遇到的问题是,无法在页面加载时将事件处理程序附加到DOM中尚不存在的元素。

As such, you need to hoist the scope, and attach the event handler to an element that's not dynamically generated, delegating the functionality by passing the target element as a parameter of on() . 这样,您需要提升作用域,并将事件处理程序附加到不是动态生成的元素,通过将目标元素作为on()的参数传递来委托功能。

In this case, you can attach it to the <ul> . 在这种情况下,您可以将其附加到<ul> You can find the last element with the CSS :last pseudo-selector: 您可以使用CSS :last伪选择器找到last元素:

 $(document).ready(function() { $("ul").on("click", "li:last", function() { $("ul").append("<li><a href='#'>Button</a></li>") }) }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li><a href="#">Button</a></li> <li><a href="#">Button</a></li> <li><a href="#">Button</a></li> </ul> 

Hope this helps! 希望这可以帮助! :) :)

If the last element could be always the same you might use prepend instead of append . 如果最后一个元素可以始终相同,则可以使用prepend而不是append Check it out: 看看这个:

 $(document).ready(function () { $('li').last().on('click', function () { $('ul').prepend('<li><a href="#">Button</a></li>') }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li><a href="#">Button</a></li> <li><a href="#">Button</a></li> <li><a href="#">Button</a></li> </ul> 

You might avoid jQuery at all and use Vainilla JavaScript instead: 您可能会完全避免使用jQuery ,而使用Vainilla JavaScript

 document.querySelector('li:last-child').addEventListener('click', () => { const template = document.createElement('template'); template.innerHTML = '<li><a href="#">Button</a></li>'; document.querySelector('ul').prepend(template.content); }); 
 <ul> <li><a href="#">Button</a></li> <li><a href="#">Button</a></li> <li><a href="#">Button</a></li> </ul> 

Note: In this example I'm using arrow functions (an ES6 feature) 注意:在此示例中,我使用箭头功能ES6功能)

Add the listener to the ul and check if it's the last child that was clicked before adding the new item. 将侦听器添加到ul,并检查它是否是添加新项之前单击的最后一个子级。

 var growingList = document.getElementById('the-list'); growingList.addEventListener('click', addToList, false); function addToList(event) { event = event || window.event; var theList = document.getElementById('the-list'); var listItems = theList.children; var lastItem = listItems.length - 1; if (event.target === listItems[lastItem]) { var htmlToAdd = '<li>' + (lastItem + 2) + '</li>'; theList.insertAdjacentHTML('beforeend', htmlToAdd); } } 
 <ul id="the-list"> <li>1</li> <li>2</li> <li>3</li> </ul> 

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

相关问题 绑定事件侦听器,并以此保留元素 - Bind event listener and keep element as this 事件侦听器仅适用于最后创建的元素 - Event listener only applying to last created element 动态事件监听器仅在最后创建的元素上起作用 - Dynamic Event Listener Working only on the Last Created Element 仅为 forEach 循环中的最后一个元素创建事件侦听器 - An event listener is only created for the last element in forEach loop 侦听器事件始终以最后一个元素的信息触发 - Listener event always triggers with last element's info 使用循环删除事件侦听器仅删除最后一个元素的侦听器 - Removing event listener using loop removes only last element's listener 在元素上注册事件侦听器 - Registering an event listener on an element 如何将 JavaScript 事件侦听器添加到无序列表的第一个元素 - How to add JavaScript event listener to first element of an unordered list 将事件侦听器添加到列表中包含的列表元素中 <ul> 在弹出菜单中 - Adding an event listener to a list element contained within a <ul> in a popup menu 事件侦听器未附加到所有元素,但仅在 JavaScript 的 for 循环中附加到最后一个元素 - Event listener not attaching to all element but attach to last one only in for loop in javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM