我想我明白你的意思,比如:https://jsfiddle.net/ve209L7j/2/
// File Groups, global scope
var files = {
'group_1': [
'file1.pdf',
'file2.pdf',
'file5.pdf',
],
'group_2': [
'file3.pdf',
'file4.pdf',
'file5.pdf',
],
'group_3': [
'file1.pdf',
'file2.pdf',
'file3.pdf',
'file4.pdf',
'file5.pdf',
],
};
// btns to create
var btns = [
{
id: 'btn1',
label: 'Files1',
custom: 'group_1'
},
{
id: 'btn2',
label: 'Files2',
custom: 'group_2'
},
{
id: 'btn3',
label: 'Files3',
custom: 'group_3'
},
];
// create btns dynamic
function createButton(btn, listener) {
const el = document.createElement('button');
el.setAttribute('id', btn.id)
el.setAttribute('data-custom', btn.custom);
el.textContent = btn.label;
el.addEventListener('click', listener);
document.body.appendChild(el);
return el;
}
// your callback listener
function btnCallback(event) {
var custom = event.currentTarget.dataset.custom;
console.log('files:', files[custom]);
}
// create buttons
btns.forEach(function(btn) {
var buttonCreated = createButton(btn, btnCallback);
// @TODO - something usefful with btn El if you need [buttonCreated]
});
老 AWSNER,在作者回复之前:
我的理解是你想使用相同的回调函数,但是每个按钮都有不同的上下文/参数。
无论哪种方式,它还抽象了侦听器绑定。
https://jsfiddle.net/ve209L7j/
Javascript:
var files = {};
function binder(ids, callback) {
ids.forEach(function(id) {
var btn = document.getElementById(id);
btn.addEventListener('click', callback);
});
}
function functionWithButtonContext(event) {
var custom = event.currentTarget.dataset.custom;
console.log('custom:', custom);
}
binder(['Button1', 'Button2', 'Button3'], functionWithButtonContext);
HTML - 我使用了“数据”属性
<button id="Button1" data-custom="btn1">
Button 1
</button>
<button id="Button2" data-custom="btn2">
Button 2
</button>
<button id="Button3" data-custom="btn3">
Button 3
</button>