简体   繁体   English

对具有数据属性的所有按钮进行onclick

[英]onclick for all buttons with a data attribute

I have three different boxes which all have a button inside. 我有三个不同的盒子,里面都有一个按钮。

I want to register an onclick event for every button with a specific data attribute. 我想为具有特定数据属性的每个按钮注册一个onclick事件。

I've started a jsfiddle, any suggestions? 我已经开始了jsfiddle,有什么建议吗?

http://jsfiddle.net/mwils/w6gofb30/ http://jsfiddle.net/mwils/w6gofb30/

 var buttons = document.querySelectorAll("button[data-donation]"); for (i = 0; i < buttons.length; i++) { document.querySelectorAll("button[data-donation]")[i].onclick = console.log(buttons[i]); } function letsGo(init) { var input = document.body.querySelector("input[name='amount']"), amount = parseInt(input.value, 10) * 100, url = "https://donate.shelter.org.uk/b?cid=152&freeamount=1&amount="; if (input.value === '' || parseInt(input.value, 10) >= 0) { window.location.href = url + init * 100; } else { window.location.href = url + amount; } } 
 <div class="shopping-item"> <p><span>£33</span> could help a family find and keep a home</p> <input type="number" name="amount" placeholder="£33" class="shopping-1-input"> <button data-donation="33" class="donate-button shopping-1-button">donate now</button> </div> <div class="shopping-item"> <p><span>£50</span> could help a family find and keep a home</p> <input type="number" name="amount" placeholder="£50" class="shopping-2-input"> <button data-donation="50" class="donate-button shopping-2-button">donate now</button> </div> <div class="shopping-item"> <p><span>£188</span> could help a family find and keep a home</p> <input type="number" name="amount" placeholder="£188" class="shopping-3-input"> <button data-donation="188" class="donate-button shopping-3-button">donate now</button> </div> 

While there are really many ways to do that i, most of the time, prefer a simple click delegation. 尽管确实有很多方法可以做到这一点,但在大多数情况下,我更喜欢简单的单击委托。 I set that on elements that contain the buttons(could be the window or document.body itself). 我在包含按钮的元素上进行设置(可以是windowdocument.body本身)。

To make it simple i show you that with a container first. 为简单起见,我首先向您展示一个容器。

<div id="container">
 <button>1</button>
 <button>2</button>
 <button>3</button>
 <button>4</button>
 <button>5</button>
</div>

here is the js 这是js

document.getElementById('container').onclick=function(e){
 if(e.target.nodeName=='BUTTON'){
  alert(e.target.textContent);
 }
}

What does this??? 这是什么???

if i click on the container it checks if the target element is a button . 如果我单击container它将检查目标元素是否为button if yes it alerts the textContent of the button. 如果是,它将警告按钮的textContent simple right? 简单吧? Doing so you avoid alot of extra variables. 这样可以避免很多额外的变量。


In your case 就你而言

document.onclick=function(e){
 if(e.target.dataset['donation']){
  alert(e.target.dataset['donation']);
 }
}

shorter

document.onclick=function(e){
 e=e.target.dataset; // reuse the variable e
 !e['donation']||alert(e['donation']);
}

using 运用

<button data-donation="33">donate now</button>

DEMO's DEMO的

http://jsfiddle.net/j8xgqfmk/ http://jsfiddle.net/j8xgqfmk/

Extra 额外

button text followed by $ symbol done with css 按钮文字,后跟$符号,使用CSS完成

http://jsfiddle.net/j8xgqfmk/1/ http://jsfiddle.net/j8xgqfmk/1/

preceded by a £ 在前面加上£

http://jsfiddle.net/j8xgqfmk/2/ http://jsfiddle.net/j8xgqfmk/2/

but returning the desidered value 但是返回期望值

Why? 为什么?

  1. No loops!!! 没有循环!
  2. Only one event handler!!!! 只有一个事件处理程序!!!
  3. Less variables!!! 变数少!!!
  4. Short code !!! 短代码 !!!
  5. Faster then multiple complex eventhandlers. 比多个复杂的事件处理程序更快。

other considerations: 其他注意事项:

var buttons = document.querySelectorAll("button[data-donation]");

for (i = 0; i < buttons.length; i++) {
 document.querySelectorAll("button[data-donation]")[i].onclick=console.log(buttons[i]);
}

Should be written 应该写

var buttons=document.querySelectorAll('button[data-donation]'),
    btnlength=buttons.length; //cache variables

for (var i = 0; i < btnlength; i++) { // var i
 buttons[i].onclick=function(){ //buttons is already defined
  console.log(this);
 }
 // and you need to pass a function to the onclick event
}

or even better 甚至更好

 function handler(e){
  console.log(this,e);
 }

 var btns=document.querySelectorAll('button[data-donation]'),
     l=btns.length;

 while(l--)btns[l].addEventListener('click',handler,false);

or the "Haters gonna hate" version “憎恨者”版本

http://jsfiddle.net/Lbk1ueme/ http://jsfiddle.net/Lbk1ueme/

var B=document.querySelectorAll('button[data-donation]'),
    L=B.length,
    I=0,
    H=function(){console.log(this)};

for(;I<L;B[I++].onclick=H);

https://stackoverflow.com/a/21353032/2450730 https://stackoverflow.com/a/21353032/2450730

if you have difficulties to understand that i can help you to write it based on your requests. 如果您难以理解,我可以根据您的要求帮助您编写。 For any other question just ask. 对于任何其他问题,请问。

keep stuff simple 保持简单

Loop through your element array (as you already are doing) and use addEventListener to bind the click event to each... 循环遍历元素数组(就像您已经做的那样),然后使用addEventListener将click事件绑定到每个元素。

 var buttons = document.querySelectorAll("button[data-donation]"); for (i = 0; i < buttons.length; i++) { buttons[i].addEventListener('click', function(event) { alert(this.getAttribute('data-donation')); // alert the value of data-donation attribute }); } 
 <div class="shopping-item"> <p><span>£33</span> could help a family find and keep a home</p> <input type="number" name="amount" placeholder="£33" class="shopping-1-input"> <button data-donation="33" class="donate-button shopping-1-button">donate now</button> </div> <div class="shopping-item"> <p><span>£50</span> could help a family find and keep a home</p> <input type="number" name="amount" placeholder="£50" class="shopping-2-input"> <button data-donation="50" class="donate-button shopping-2-button">donate now</button> </div> <div class="shopping-item"> <p><span>£188</span> could help a family find and keep a home</p> <input type="number" name="amount" placeholder="£188" class="shopping-3-input"> <button data-donation="188" class="donate-button shopping-3-button">donate now</button> 

The problem is you are not attaching events correctly to the element. 问题是您没有将事件正确地附加到元素。 You are assigning console.log and not a function to it. 您正在分配console.log而不是功能。 Seconds querySelectorAll is expensive. Seconds querySelectorAll非常昂贵。 You should not keep looking things up in a loop. 您不应该一直循环查找。 Create a variable and store the live html node collection it returns into it. 创建一个变量并存储它返回的实时html节点集合。

 var btns = document.querySelectorAll("button[data-donation]"); for (var i=0; i<btns.length; i++) { btns[i].onclick = function() { console.log(this); console.log(this.getAttribute("data-donation")); } } function letsGo(init) { var input = document.body.querySelector("input[name='amount']"), amount = parseInt(input.value, 10) * 100, url = "https://donate.shelter.org.uk/b?cid=152&freeamount=1&amount="; if (input.value === '' || parseInt(input.value, 10) >= 0) { window.location.href = url + init * 100; } else { window.location.href = url + amount; } } 
 <div class="shopping-item"> <p><span>£33</span> could help a family find and keep a home</p> <input type="number" name="amount" placeholder="£33" class="shopping-1-input"> <button data-donation="33" class="donate-button shopping-1-button">donate now</button> </div> <div class="shopping-item"> <p><span>£50</span> could help a family find and keep a home</p> <input type="number" name="amount" placeholder="£50" class="shopping-2-input"> <button data-donation="50" class="donate-button shopping-2-button">donate now</button> </div> <div class="shopping-item"> <p><span>£188</span> could help a family find and keep a home</p> <input type="number" name="amount" placeholder="£188" class="shopping-3-input"> <button data-donation="188" class="donate-button shopping-3-button">donate now</button> </div> 

You've got the selector right already, ie var buttons = document.querySelectorAll("button[data-donation]") is pulling in all the buttons having data-donation , but there's no need to do another querySelectorAll inside your loop, you just need to reference each button in your result with buttons[i] . 您已经有了正确的选择器,即var buttons = document.querySelectorAll("button[data-donation]")正在拉入所有具有data-donation的按钮,但是无需在循环内执行另一个querySelectorAll ,只需要使用buttons[i]引用结果中的每个按钮。

Your other mistake is setting onclick = console.log() , instead of onclick = function() { console.log() } . 您的另一个错误是设置onclick = console.log() ,而不是onclick = function() { console.log() } So all you need to change to get it working is: 因此,您只需进行以下更改即可使其正常工作:

var buttons = document.querySelectorAll("button[data-donation]");

for (i = 0; i < buttons.length; i++) {
    var button = buttons[i];
    buttons[i].onclick = function() { console.log(button) };
}

http://jsfiddle.net/w6gofb30/4/ http://jsfiddle.net/w6gofb30/4/

document.querySelectorAll("button[data-donation]").every(function(e,i,a){
    e.addEventListener("click", function(){
        console.log(this);
        console.log(this.getAttribute("data-donation"));
    }, false);
});

but before this u need: 但在此之前,您需要:

NodeList.prototype.every = function(f){
    for(var k=0;k<this.length;k++)
        f(this[k],k,this);
}

http://jsfiddle.net/sa0ezut7/ http://jsfiddle.net/sa0ezut7/

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

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