javascript将click事件监听器添加到类中

时间:2021-11-27 20:04:03

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

我有一个删除id列表视图。我想为具有特定类的所有元素添加一个监听器并执行确认警报。

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

我的问题是,这似乎只是将侦听器添加到它找到的第一个类中。我试图使用querySelectorAll但它没有用

 <script>
        var deleteLink = document.querySelector('.delete');

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

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

list:

列表:

<?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();
     ?>

4 个解决方案

#1


88  

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

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

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

Then you would loop:

然后你会循环:

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();
        }
    });
}

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

另外,只有在确认=== false时才应该使用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().

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

Demo: http://jsfiddle.net/Rc7jL/3/

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


ES6 version

ES6版本

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

通过使用Array.prototype.forEach迭代而不是for循环,您可以使它更清晰(并且更安全地闭环):

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();
        }
    });
});

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

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

#2


37  

The problem with using querySelectorAll and a for loop is that it creates a whole new event handler for each element in the array.

使用querySelectorAll和for循环的问题是它为数组中的每个元素创建一个全新的事件处理程序。

Sometimes that is exactly what you want. But if you have many elements, it may be more efficient to create a single event handler and attach it to a container element. You can then use event.target to refer to the specific element which triggered the event:

有时这正是你想要的。但是,如果您有许多元素,那么创建单个事件处理程序并将其附加到容器元素可能更有效。然后,您可以使用event.target来引用触发事件的特定元素:

document.body.addEventListener("click", function (event) {
  if (event.target.classList.contains("delete")) {
    var title = event.target.getAttribute("title");

    if (!confirm("sure u want to delete " + title)) {
      event.preventDefault();
    }
  }
});

In this example we only create one event handler which is attached to the body element. Whenever an element inside the body is clicked, the click event bubbles up to our event handler.

在这个例子中,我们只创建一个附加到body元素的事件处理程序。每当单击body中的元素时,click事件就会冒泡到我们的事件处理程序。

#3


7  

A short and sweet solution, using ES6:

使用ES6的简短而甜蜜的解决方案:

document.querySelectorAll('.input')
      .forEach(input => input.addEventListener('focus', this.onInputFocus));

#4


6  

You have to use querySelectorAll as you need to select all elements with the said class, again since querySelectorAll is an array you need to iterate it and add the event handlers

您必须使用querySelectorAll,因为您需要选择具有所述类的所有元素,因为querySelectorAll是一个需要迭代它并添加事件处理程序的数组

var deleteLinks = document.querySelectorAll('.delete');
for (var i = 0; i < deleteLinks.length; i++) {
    deleteLinks[i].addEventListener('click', function (event) {
        event.preventDefault();

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

#1


88  

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

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

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

Then you would loop:

然后你会循环:

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();
        }
    });
}

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

另外,只有在确认=== false时才应该使用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().

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

Demo: http://jsfiddle.net/Rc7jL/3/

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


ES6 version

ES6版本

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

通过使用Array.prototype.forEach迭代而不是for循环,您可以使它更清晰(并且更安全地闭环):

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();
        }
    });
});

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

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

#2


37  

The problem with using querySelectorAll and a for loop is that it creates a whole new event handler for each element in the array.

使用querySelectorAll和for循环的问题是它为数组中的每个元素创建一个全新的事件处理程序。

Sometimes that is exactly what you want. But if you have many elements, it may be more efficient to create a single event handler and attach it to a container element. You can then use event.target to refer to the specific element which triggered the event:

有时这正是你想要的。但是,如果您有许多元素,那么创建单个事件处理程序并将其附加到容器元素可能更有效。然后,您可以使用event.target来引用触发事件的特定元素:

document.body.addEventListener("click", function (event) {
  if (event.target.classList.contains("delete")) {
    var title = event.target.getAttribute("title");

    if (!confirm("sure u want to delete " + title)) {
      event.preventDefault();
    }
  }
});

In this example we only create one event handler which is attached to the body element. Whenever an element inside the body is clicked, the click event bubbles up to our event handler.

在这个例子中,我们只创建一个附加到body元素的事件处理程序。每当单击body中的元素时,click事件就会冒泡到我们的事件处理程序。

#3


7  

A short and sweet solution, using ES6:

使用ES6的简短而甜蜜的解决方案:

document.querySelectorAll('.input')
      .forEach(input => input.addEventListener('focus', this.onInputFocus));

#4


6  

You have to use querySelectorAll as you need to select all elements with the said class, again since querySelectorAll is an array you need to iterate it and add the event handlers

您必须使用querySelectorAll,因为您需要选择具有所述类的所有元素,因为querySelectorAll是一个需要迭代它并添加事件处理程序的数组

var deleteLinks = document.querySelectorAll('.delete');
for (var i = 0; i < deleteLinks.length; i++) {
    deleteLinks[i].addEventListener('click', function (event) {
        event.preventDefault();

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

相关文章