質問

var fbToggle = document.getElementById("fbToggle");

and later in the script

fbToggle.addEventListener("click", toggle("fbContainer"));

Console tells me that fbToggle is NULL

This is in the document though.

<input type="checkbox" id="fbToggle">

I wasnt using eventListener before, so maybe there is a special order of declaration i'm missing ?

EDIT :

entire js :

function toggle(target) {
var obj = document.getElementById(target);
display = obj.style.display;
if (display == "none") {display = "block"}
else {display = "none"}
}

function init() {
var fbToggle = document.getElementById("fbToggle");
var twitToggle = document.getElementById("twitToggle");
var pinToggle = document.getElementById("pinToggle");   
console.log(fbToggle); // NULL
fbToggle.addEventListener("click", toggle("fbContainer"));
twitToggle.addEventListener("click", toggle("twitContainer"));
pinToggle.addEventListener("click", toggle("pinContainer"));
}

window.onload = init();

HTML is way too long.but JS is in head, called from external file. Also i'm not in quirk mode.

役に立ちましたか?

解決 2

In JavaScript, putting brackets after a function name causes it to be called. If you want to reference a function without calling it you must not put brackets after the name:

window.onload = init(); // this calls init() immediately
window.onload = init; // this correctly stores init in window.onload

The same applies to toggle(). If you need to pre-specify some of the arguments you can wrap it in an anonymous function:

fbToggle.addEventListener("click", function() { toggle("fbContainer"); });

or you can use bind:

fbToggle.addEventListener("click", toggle.bind(null, "fbContainer"));

他のヒント

It is not clear where "later in the script" is. If it is in different scope definitely it is not going to work. Suggesting you to keep everything in a global object if possible so that you can access from different places in the script.

window.globals = {};
window.globals.fbToggle = document.getElementById("fbToggle");


window.globals.fbToggle.addEventListener("click", function () {
    toggle("fbContainer")
});

function toggle(container) {
    alert(container);
}

http://jsfiddle.net/ST938/

Another point is addEventListener expects a function or function idenitifier, NOT a function call.

addEventListener("click", toggle("fbContainer"));  // wrong
addEventListener("click", toggle);  // correct

So if you want to pass a parameter

window.globals.fbToggle.addEventListener("click", function () {
    toggle("fbContainer")
});

function toggle(container) {
    alert(container);
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top