【问题标题】:Browser Extension's creating dynamic buttons with dynamic links浏览器扩展创建带有动态链接的动态按钮
【发布时间】: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


    【解决方案1】:

    我找到了一种方法,方法是创建一个a 元素,通过a.href = tmpLink 设置href 并将按钮作为子元素附加到a 元素。最后的功能是:

    function createSiteButton(numBtns, b_id, b_class, b_text, b_link, b_bg)
    {
        var outputElem = document.getElementById('output');
        
        // check if the input text is an array
        if (Array.isArray(b_text))
        {
            //var tmpLink = null;
            // create the new set of buttons
            for (i= 0; i < numBtns; i++)
            {
                var a = document.createElement('a');
                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;
                
                a.href = tmpLink;
                
                a.appendChild(newButton);
                divID.appendChild(a);
                
                button_array[i] = newButton;
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-10
      • 2011-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-14
      相关资源
      最近更新 更多