admin管理员组

文章数量:1289868

So i have the following jQuery:

<script type="text/javascript">

    // Init.
    $(function () {

        // Wire up the search box.
        $('#searchButton').click(
            search($('#query').val(),
                $('aaa').val(),
                $('bbb').val()
            ));
    });

</script>

But when i first hit the page, the search function is getting fired (because I put a breakpoint in there).

I thought my code (above) is just saying: Wire up the click event AND when someone clicks that button, the following code is called => search function with the following 3 arguments).

Can anyone tell me what I've done wrong, please?

So i have the following jQuery:

<script type="text/javascript">

    // Init.
    $(function () {

        // Wire up the search box.
        $('#searchButton').click(
            search($('#query').val(),
                $('aaa').val(),
                $('bbb').val()
            ));
    });

</script>

But when i first hit the page, the search function is getting fired (because I put a breakpoint in there).

I thought my code (above) is just saying: Wire up the click event AND when someone clicks that button, the following code is called => search function with the following 3 arguments).

Can anyone tell me what I've done wrong, please?

Share Improve this question asked Jan 4, 2013 at 1:52 Pure.KromePure.Krome 87k121 gold badges425 silver badges687 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 8

Because it expects a function reference. What you're doing is executing search() and passing that result as the reference.

<script type="text/javascript">

    // Init.
    $(function () {

        // Wire up the search box.
        $('#searchButton').click(function() {
                search($('#query').val(),
                    $('aaa').val(),
                    $('bbb').val()
                ));
            }
    });

</script>

You should wrap your handler code inside an anonymous function.

Otherwise search() will get evaluated and the result will be applied to the click handler.

Try this:

$(function () {
    $('#searchButton').click(function () {
        search( $('#query').val(),
                $('aaa').val(),
                $('bbb').val() 
        );
    });
});

Because you are calling function "click" with one parameter, the return of "search(); and it is not a function callback.

How about this?

<script type="text/javascript">

    // Init.
    $(function () {

        // Wire up the search box.
        $('#searchButton').click(function() {
            search($('#query').val(),
                $('aaa').val(),
                $('bbb').val()); }
            );
    });

</script>

Attach anonymous function on click event, and call search($('#query').val(),$('aaa').val(),$('bbb').val()); in function.

    $('#searchButton').live('click',function() {
        whatever...
    });

本文标签: