gpt4 book ai didi

javascript - 具有特定变量的唯一 ID,以使用所述变量调用数组中的函数

转载 作者:行者123 更新时间:2023-12-03 12:21:15 24 4
gpt4 key购买 nike

如果这是 JavaScript 和 Electron.js 的新手,我提前道歉。
在这个例子中,我有 Btn1, Btn2, Btn3每个按钮都链接到一个特定的变量。
一个 onclick event每个按钮的监听器都连接到同一个 function和或 array .
根据单击的按钮,它将使用链接到按下的按钮的变量来运行该函数。

let buttons = [btn1, btn2, btn3]

let open = document.getElementById('Btn1')
open.addEventListener('click', (event) =>{
let btn1_value = 1
//2 more of these for each button
})
}
我不只是有一组预设函数或一系列 if-case 语句。
当我试图动态地允许用户使用相同的功能向我的软件添加按钮时。
但是,使用存储在数组中的不同数据(在本例中为文件)。
由于我目前的知识,我决定尝试这样的方法。
使用 push() 在数组中添加和删除数据更易于管理(对我来说)和 pop() .
而不是必须为每个创建的按钮创建多个功能,尤其是动态的。
非常感谢任何帮助或指导。

最佳答案

我想我明白你的意思,类似这样: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,在作者回复之前:
我的理解是您想使用相同的回调函数,但每个按钮都有不同的上下文/参数。
无论哪种方式,它还抽象了监听器绑定(bind)。
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>

关于javascript - 具有特定变量的唯一 ID,以使用所述变量调用数组中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65415067/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com