开发者

Why is my function called two times?

    $(document).ready(functi开发者_如何学运维on () {
 doSomething(1);    
 $('#pp').click( doSomething(2) );//why is this called?? I didn't click the button..
});

function doSomething(v) {
 alert(v);
}
</script>

<body>

<input type="button" id="pp" value="asdf" />

I need a function to be called on load and click. But somehow doSomething() is called two times on load. What's going on..??


Change the ready fragment to

$(document).ready(function() {
  doSomething(1);
  $('#pp').click(function() {
    doSomething(2);
  });
});


$(document).ready(function () {
 doSomething(1);    
 $('#pp').click( function(){doSomething(2);} );
});


You need to wrap what you pass to .click() in a function {}. Otherwise it executes when the .click() line executes and the result is passed to .click().


I think there's an error in your event-binding. It should be:

$('#pp').bind('click', function () { doSomething(2); });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜