javascript - 通过数组和 FOR 循环添加事件监听器

标签 javascript arrays events for-loop listener

最近几天遇到了一些问题。我正在尝试尽可能地简化我的代码,现在我已经到了尝试通过 JavaScript 添加事件监听器的阶段,以便我的 HTML 看起来更整洁。

-HTML 段-

<input type="button" id="googleSearchButton" />
<input type="button" id="youtubeSearchButton" />
<input type="button" id="wikiSearchButton" />
<input type="button" id="facebookSearchButton" />
<input type="button" id="twitterSearchButton" />
<input type="button" id="tumblrSearchButton" />
<input type="button" id="dropboxSearchButton" />

JavaScript 段

var contIDArray = ["google", "youtube", "wiki", "facebook", "twitter", "tumblr", "dropbox"];

window.load = initAll();
function initAll(){
    applyProperties();
}

function applyProperties(){
        for (var i = 0; i < contIDArray.length; i++){
            addEventListeners(contIDArray[i] + "SearchButton");
        }
}

function addEventListeners(id){
    document.getElementById(id).addEventListener("click", testAlert(id), false);
}

function testAlert(id){
    alert(id + " clicked")
}

理论

我希望您能看到,FOR 循环将一直循环,直到用完容器数组中的值。每次它都会输出数组中的位置,然后是“SearchButton”。例如,第一次循环会输出“googleSearchButton”,第二次会输出“youtubeSearchButton”等等。

现在,我知道 FOR 循环适用于应用属性,因为我使用它在项目的其他部分应用按钮值和文本框占位符文本。

我已经让它添加了一个简单的测试函数(“testAlert()”)并将其设置为传递调用它的元素的 ID。我已经设置好了,一旦添加了事件监听器,我只需点击每个按钮,它就会提醒它的 ID 并告诉我它已被点击。

问题

现在,从理论上讲,我认为这可行。但似乎 FOR 循环触发了“addEventListeners”函数,该函数又添加了事件监听器以在单击时触发“testAlert”。但它只会在添加事件监听器后立即触发“testAlert”函数,而不会在您单击时触发。

如果这看起来有点难以理解,我深表歉意,我的解释总是过长。希望您能够从我的代码中看到我试图完成的事情,而不是我的解释。

帮助将不胜感激。 :)

最佳答案

你很接近这里,但有一些问题。

首先,您不能只执行 id.addEventListener。您需要执行 document.getElementById(id).addEventListenerid 只是一个字符串,您需要一个 DOMElement。

其次,当您执行 testAlert(id) 时,您正在运行该函数,然后将其返回值 (undefined) 指定为事件监听器。你需要传递一个函数。像这样:

id.addEventListener("click", function(){
  testAlert(this.id); // this is the DOMElement you clicked on
}, false);

尽管我建议为所有按钮添加一个类,然后像那样添加事件。

<input type="button" id="googleSearchButton" class="searchButton" />
<input type="button" id="youtubeSearchButton" class="searchButton" />
<input type="button" id="wikiSearchButton" class="searchButton" />
<input type="button" id="facebookSearchButton" class="searchButton" />
<input type="button" id="twitterSearchButton" class="searchButton" />
<input type="button" id="tumblrSearchButton" class="searchButton" />
<input type="button" id="dropboxSearchButton" class="searchButton" />

然后:

var buttons = document.getElementsByClassName('searchButton');
for(b in buttons){
   if(buttons.hasOwnProperty(b)){
     buttons[b].addEventListener("click", function(){
        testAlert(this.id); // this is the DOMElement you clicked on
     }, false);
   }
}

注意:addEventListenergetElementsByClassName 可能不适用于所有浏览器(我的意思是它们可能不适用于 IE)。这就是为什么很多网站使用 JavaScript 库,比如 jQuery . jQuery 为您处理所有跨浏览器的事情。如果你想使用 jQuery,你可以这样做:

$('.searchButton').click(function(){
  testAlert(this.id);
});

注意2:在JavaScript中,函数是变量,可以作为参数传递。

document.getElementById(id).addEventListener('click', testAlert, false);

注意 testAlert 之后没有 (),我们传递的是函数本身,当你执行 testAlert() 时,你传递它的返回值。如果您这样做,testAlert 将需要稍微修改一下:

function testAlert(){
    alert(this.id + " clicked")
}

关于javascript - 通过数组和 FOR 循环添加事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8657444/

相关文章:

javascript - 如何用javascript迭代json?

javascript - 如何使用jquery为div动态添加点击事件

c# - 第一次显示控件后会立即发生什么事件?

objective-c - 在Cocoa/Obj-C中,如何捕获cmd-c事件?

Javascript/Jquery .html() 仅替换一次

Javascript 数组 filter() 与 bind()

javascript - 自动播放无法在我的 Javascript Slider 上运行

PHP:检查数组中的所有值是否都小于 x

php - 将 txt 文件的内容分解为数组

javascript - 从 Javascript 中的数组中删除某些元素