Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

jquery - Why is this javascript function running without being called?

$(document).ready(SetupButtonClicks());

function SetupButtonClicks() {
    $('#btnJavaPHP').click(DoPHPStuff());
}

function DoPHPStuff() {
    //stuff
}

I have this code in my javascript file, when I debug it I see it call SetupButtonClicks() like it should but after that is done it calls DoPHPStuff(). DoPHPStuff() should only be called when btnJavaPHP is clicked. What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Change your SetupButtonClicks function:

$('#btnJavaPHP').click(DoHPStuff);

The way you've got it coded, you're telling Javascript to call the function, not to use it as the "click" handler. The parentheses are an operator that causes a function to be called.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...