将Click事件侦听器添加到具有相同类的元素 [英] Adding click event listener to elements with the same class

查看:57
本文介绍了将Click事件侦听器添加到具有相同类的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个删除ID的列表视图.我想为具有特定类的所有元素添加一个侦听器,并发出确认警报.

I have a list view for delete id. I'd like to add a listener to all elements with a particular class and do a confirm alert.

我的问题是,这似乎只会将侦听器添加到具有找到的类的第一个元素.我尝试使用querySelectorAll,但是没有用.

My problem is that this seems to only add the listener to the first element with the class it finds. I tried to use querySelectorAll but it didn't work.

var deleteLink = document.querySelector('.delete');

deleteLink.addEventListener('click', function(event) {
    event.preventDefault();

    var choice = confirm("sure u want to delete?");
    if (choice) {
        return true;
    }
});

列表:

<?php 
    while($obj=$result->fetch_object())
    {
        echo '<li><a class="delete" href="removeTruck.php?tid='.$obj->id.'">'.$obj->id.'</a>'
            . '<a href="#" class="delete"></a>
                      </li>'."\n";
    }
    /* free result set */
    $result->close();       
    $mysqli->close();
?>

推荐答案

您应使用querySelectorAll.它返回NodeList,但是querySelector仅返回找到的第一个元素:

You should use querySelectorAll. It returns NodeList, however querySelector returns only the first found element:

var deleteLink = document.querySelectorAll('.delete');

然后您将循环:

for (var i = 0; i < deleteLink.length; i++) {
    deleteLink[i].addEventListener('click', function(event) {
        if (!confirm("sure u want to delete " + this.title)) {
            event.preventDefault();
        }
    });
}

此外,仅当confirm === false时,才应阻止Default.

Also you should preventDefault only if confirm === false.

还值得注意的是,return false/true仅对与onclick = function() {...}绑定的事件处理程序有用.对于addEventListening,您应该使用event.preventDefault().

It's also worth noting that return false/true is only useful for event handlers bound with onclick = function() {...}. For addEventListening you should use event.preventDefault().

演示: http://jsfiddle.net/Rc7jL/3/

ES6版本

您可以使其更加整洁(并且更安全 closure-in-loop明智),方法是使用 Array.prototype .forEach 迭代而不是for循环:

You can make it a little cleaner (and safer closure-in-loop wise) by using Array.prototype.forEach iteration instead of for-loop:

var deleteLinks = document.querySelectorAll('.delete');

Array.from(deleteLinks).forEach(link => {
    link.addEventListener('click', function(event) {
        if (!confirm(`sure u want to delete ${this.title}`)) {
            event.preventDefault();
        }
    });
});

上面的示例使用 Array.from 和来自ES2015标准的模板字符串.

Example above uses Array.from and template strings from ES2015 standard.

这篇关于将Click事件侦听器添加到具有相同类的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆