JavaScript - Having trouble with a click event
I am using sizzle to select various parts of the DOM.
My code is below. The problem is that the onmouseup event is being triggered when the page is loaded instead of when the user interacts with the page.
Can someone explain why this is please.
Thanks.
// Effects object
var effects = {
// Display an object
show : function(obj) {
obj.style.display = 'block';
},
// Hide an object
hide : function(obj) {
obj.style.display = 'hide';
},
// Toggle
toggle : function(obj) {
if (obj instanceof Array) {
alert('array');
} else {
alert('single');
}
}
}
// Selector Class
var s = Sizzle;
window.onload = function() {
s('#toggle-content').onmouseup = effects.toggle(s('.hidden-content'));
}
HTML as requested:
<div class="page-content box create-page">
开发者_高级运维 <h1><span class="left">Create Page</span><a class="right" id="toggle-content" href="#">Expand</a></h1>
<div class="hidden-content">
...
</div>
</div>
you need to pass it as an anonymous function eg.
window.onload = function() {
s('#toggle-content').onmouseup = function(){effects.toggle(s('.hidden-content'));}
}
It's because you're calling effects.toggle
in the expression. You should actually bind the function to avoid calling it.
function bind() { var initArgs = array(arguments); var fx = initArgs.shift(); var tObj = initArgs.shift(); var args = initArgs; return function() { return fx.apply(tObj, args.concat(array(arguments))); }; } function array(a) { var r = []; for (var i = 0; i < a.length; i++) r.push(a[i]); return r; } window.onload = function() { s('#toggle-content').onmouseup = bind(effects.toggle, null, s('.hidden-content')); }
精彩评论