onclick所有具有数据属性的按钮

时间:2015-05-19 12:10:01

标签: javascript

我有三个不同的盒子,里面都有一个按钮。

我想为每个具有特定数据属性的按钮注册onclick事件。

我已经开始了jsfiddle,有什么建议吗?

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>

5 个答案:

答案 0 :(得分:2)

虽然有很多方法可以做到这一点,但大多数时候,我更喜欢简单的点击授权。我在包含按钮的元素上设置了它(可以是windowdocument.body本身。)

为了简单起见,我首先向您展示容器。

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

这是js

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

这是什么???

如果我点击container,它会检查目标元素是否为button。 如果是,它会提醒按钮的textContent。简单吧? 这样做可以避免很多额外的变量。

在你的情况下

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

更短的

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

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

<强>样本的

http://jsfiddle.net/j8xgqfmk/

<强>附加

按钮文字,后跟用css

完成的$符号

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

前面有£

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

但返回了所需的值

<强>为什么吗

  1. 没有循环!!!
  2. 只有一个事件处理程序!!!!
  3. 少变量!!!
  4. 短代码!!!
  5. 然后更快,然后是多个复杂的事件处理程序。
  6. 其他注意事项:

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

    应该写

    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
    }
    

    甚至更好

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

    “Haters会讨厌”版本

    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

    如果您难以理解我可以根据您的要求帮助您编写它。对于任何其他问题,请问。

    保持简单

答案 1 :(得分:1)

遍历你的元素数组(正如你已经做的那样)并使用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>

答案 2 :(得分:1)

问题是您没有正确地将事件附加到元素。您正在分配console.log而不是它的功能。秒查询选择器都很昂贵。你不应该继续在循环中寻找东西。创建一个变量并存储它返回的实时html节点集合。

&#13;
&#13;
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;
    }
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

你已经拥有了选择器,即var buttons = document.querySelectorAll("button[data-donation]")正在拉入data-donation的所有按钮,但是你不需要在你的循环中再做一个querySelectorAll,你只需要使用buttons[i]引用结果中的每个按钮。

您的另一个错误是设置onclick = console.log(),而不是onclick = function() { console.log() }。因此,您需要进行更改以使其正常工作:

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/

答案 4 :(得分:0)

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

但在此之前你需要:

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

http://jsfiddle.net/sa0ezut7/