2017-09-23 20 views
1

我把東西放在一起,它有很多的按鈕,每個按鈕做不同的事情。Javascript jQuery多個按鈕和點擊事件

我已經做到了是這樣的方式:

$("#somebutton").click(function() { 
    //Do something  
}); 

$("#someotherbutton").click(function() { 
    //Do something else   
}); 

$("#someotherbutton").click(function() { 
    //Do something else   
}); 

$("#someotherbutton").click(function() { 
    //Do something else   
}); 

...等等...一個

我的問題是...

是否有更好的方法來做到這一點,例如有一個數組與按鈕ID和這個調用函數後點擊事件?

+0

查看我的更新回答。 –

回答

2

如果存儲的按鈕以及它們在陣列/對象結構對應click回調函數,可以壓縮此,然後使通用函數在合適的時間調用每個:

$("button").click(function(evt) { 
 
    // this binding is lost inside of forEach 
 
    var id = this.id; 
 
    // Loop over each stored object in the array... 
 
    var result = buttonsAndFunctions.forEach(function(obj){ 
 
     // If the current object.button matches the button.id, invoke the function 
 
     // Since the function won't directly recieve the event, we'll pass the event 
 
     // to the function: 
 
     (obj.button === id) ? obj.fn(evt) : ""; 
 
    }); 
 
}); 
 

 

 
var buttonsAndFunctions = [ 
 
    // I'm using the same function for each button here only for demonstration 
 
    // In reality, they'd each be different 
 
    { button : "btn1", fn : function(evt){ console.log(evt.target.id + " was clicked"); } }, 
 
    { button : "btn2", fn : function(evt){ console.log(evt.target.id + " was clicked"); } }, 
 
    { button : "btn3", fn : function(evt){ console.log(evt.target.id + " was clicked"); } }, 
 
    { button : "btn4", fn : function(evt){ console.log(evt.target.id + " was clicked"); } } 
 
]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button id="btn1">Button 1</button> 
 
<button id="btn2">Button 2</button> 
 
<button id="btn3">Button 3</button> 
 
<button id="btn4">Button 3</button>

2

在我的項目中,我使用某種「約定」。 所有觸發某些動作的可點擊元素都有特殊類,例如「btn-action」。該元素具有「數據操作」屬性以及要執行的操作信息。

<button class="btn-action" data-action="something" data-mydata="1">click</button> 

<script type="text/javascript"> 
;+function() { 

    $('.btn-action').click(function(event) { 

     let action = $(this).data('action') 
     if(typeof actions[action] !== undefined) { 
      actions[action](event) 
     } 
    }) 

    const actions = { 

     something : function(e) { 
      let button = $(e.currentTarget), 
       mydata = button.data('mydata') 
     }, 

     somethingElse : function(e) { 

     } 
    } 
}(); 
</script> 

我不認爲這是最好的解決方案,但這有助於我保持代碼清潔。