【发布时间】:2021-04-13 17:48:38
【问题描述】:
我正在尝试创建一个浏览器扩展弹出窗口(在 JS 中),它创建了许多带有打开不同网页的链接的按钮。该函数采用许多参数,主要参数是 b_link,它是网站的 URL 数组。出于某种原因,只有数组中的最后一个 URL 应用于所有创建的按钮。
我不完全确定问题出在哪里,我可以推测,但我认为这不会有成效。我确实注意到并且必须补偿的一件事是在 lambda 函数中使用 b_link。仅使用b_link[i],lambda 函数只看到未定义,因此没有打开网页,但使用var tmpLink = b_link[i]; 至少可以获得函数的链接并允许打开网页。
我应该如何制作这些按钮,以便它们都有自己的链接,而不仅仅是数组中的最后一个?
有问题的函数:
function createSiteButton(numBtns, b_id, b_class, b_text, b_link, b_bg)
{
// check if the input text is an array
if (Array.isArray(b_text))
{
// create the new set of buttons
for (i= 0; i < numBtns; i++)
{
var newButton = document.createElement('button');
var tmpLink = b_link[i];
newButton.id = b_id;
newButton.class = b_class;
newButton.innerHTML = b_text[i];
newButton.style.background = b_bg;
newButton.addEventListener("click", function()
{
if (tmpLink)
{
window.open(tmpLink, "_blank");
}
});
button_array[i] = newButton;
}
// add the new buttons the screen
for (i= 0; i < numBtns; i++)
{
divID.appendChild(button_array[i]);
}
}
}
【问题讨论】:
标签: javascript arrays browser parameter-passing webbrowser-control