选择框导航:寡妇在页面加载时打开而不是更改 [英] Select Box Navigation: widow opening on page load rather than change
问题描述
我有一个带有某些选项的选择框。我想允许用户选择一个选项,然后转到该选项的value属性中存储的URL。但是,我的脚本会在页面加载而不是更改时继续打开新窗口。为什么?!
I've got a select box with some options. I want to allow a user to choose an option and then be taken to a URL stored in that option's value attribute. However, my script keeps opening the new window on page load, not on change. Why?! Help!
function selectBoxNav() {
"use strict";
var mySelectBox = document.getElementById('mySelectBox');
var myOption = mySelectBox.options[mySelectBox.selectedIndex];
var myURL = myOption.value;
function newWindow() {
window.open(myURL);
}
mySelectBox.addEventListener('change', newWindow(), false);
}
window.addEventListener('DOMContentLoaded', selectBoxNav(), false);
推荐答案
您需要将函数传递给 addEventListener()
,但您要调用它并传递其返回值。 newWindow()
调用该函数。要传递它,您应该删除括号: mySelectBox.addEventListener(’change’,newWindow,false);
You need to pass the function to addEventListener()
, but instead you're calling it and passing its return value. newWindow()
calls the function. To pass it you should remove the parentheses: mySelectBox.addEventListener('change', newWindow, false);
这篇关于选择框导航:寡妇在页面加载时打开而不是更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!