简体   繁体   中英

Click event only triggers once, after the page is loaded

I have a click event in jQuery. The desired behavior is for a function to execute every time the link is clicked. However, the actual behavior is that the page loads and then the function is executed once and never again. The offending code follows. Thanks!

<!DOCTYPE html>
<head>
<meta charset="utf-8">

<style>
#sub {
position:fixed;
z-index:999;
margin-top:180px;
margin-left:200px;
display:none;}
</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<script>
function showdiv(divid) {
   $('.menu').hide();
   $('#'+divid).fadeToggle('slow');
};
$(document).ready(function(){
    $('a#opt1').click(showdiv('sub'));
    $('a#opt2').click(function(){$('.menu').hide();});
}); 
</script>
</head>
<body>
    <li><a id="opt1" href="#">Option1</a></li>
    <li><a id="opt2" href="#">Option2</a></li>
</ul>
<ul id="sub">
    <li><a href="#">Mission</a></li>
    <li><a href="#">Press</a></li>
</ul>

$('a#opt1').click(showdiv('sub')); will run the function showdiv immediately, setting the return value as what is called onclick (in this case, nothing, hence your click handler seems to not work).

You should wrap this in an anonymous function.

$('a#opt1').click(function() { showdiv('sub') });

You need to wrap the function in an anonymous function:

$('a#opt1').click(function() {
    showdiv('sub');
});

You are supposed to pass the function reference to .click . In your case, you passed the returned value of you function instead of the actual function. Long story short, you should wrap it with function(){} :

$('a#opt1').click(function(){
    showdiv('sub');
});

The jQuery documentation on .click actually states that you have to pass a function, but instead you passed undefined in your example. That is why it only executed once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM