jquery click event issues

2019-08-24 06:27发布

问题:

I'm having some issues with .click() event under Internet Explorer and Chrome.

So, I've got this menu of filters:

<div id="filter-checkboxes" style="text-align: left; margin-bottom: 20px;">
    <input type="checkbox" id="crop-checkbox" onclick="init_filter('crop');" />
    <span id="crop-span">Crop</span>
    <br />

    <input type="checkbox" id="resize-checkbox" onclick="init_filter('resize');" />
    <span id="resize-span">Resize</span>
    <br />

    [...]
</div>

The init_filter(filter) calls at the end another function that sends a ajax req

function apply(action)
{
    var apply_btn = $("#apply-filter-btn");
    var values = null;

    $(document).ready(function(){
        apply_btn.unbind("click");
        apply_btn.click(function(){
            switch (action)
            {
                case "crop":
                    values  =   "x=" + $("#x").val() + "&y=" + $("#y").val() +
                    "&w="   + $("#w").val() + "&h=" + $("#h").val();

                    if ($("#w").val() !== "0" && $("#h").val() !== "0")
                        apply_send_req(action, apply_btn, values);
                break;
            }
        });
    });
}

The issue is that there is a delay before the actual request is sent. This works great only in Firefox... So what I'm asking is what can I do to prevent this ?

回答1:

Bearing in mind this code is all inside a function, I think you should drop the document ready section. If you are calling "apply" on load, wrap the call up in the document ready statement, rather than chaining it inside a function. This may solve your problem as you may be adding to the document ready event AFTER it has fired.

function apply(action)
{
    var apply_btn = $("#apply-filter-btn");
    var values = null;

    apply_btn.unbind("click");
    apply_btn.click(function(){
        switch (action)
        {
            case "crop":
                values  =   "x=" + $("#x").val() + "&y=" + $("#y").val() +
                "&w="   + $("#w").val() + "&h=" + $("#h").val();

                if ($("#w").val() !== "0" && $("#h").val() !== "0")
                    apply_send_req(action, apply_btn, values);
            break;
        }
    });
}


回答2:

Just a stab in the dark, should you not be defining your apply_btn inside the document ready section, otherwise there's a risk it may not exist and your var will be undefined?

$(document).ready(function(){
    var apply_btn = $("#apply-filter-btn"); // <-- inside .ready()


标签: jquery click