简体   繁体   中英

jQuery assign click event handler on page load

I want to assign a click handler for button in the page load function. I then want to handle the actual click of the button at a later time with the following code snippet:

 $("#finish").off('click').on('click', function () {
            var sku = $("#productSKU").val();
            var name = $("#productName").val();
            var affiliateId = $("#AffiliateID").val();
            var Errors = "";
            var category = null;
            var defaultName = $('#defaultImgName').val();

            if ($("#childCategories_" + categoryLevel).length == 0) {
                category = $("#categoryList").val();
            }
            else if ($("#childCategories_" + categoryLevel).val() == 0) {
                category = null;
            }
            else {
                category = $("#childCategories_" + categoryLevel).val();
            }

            if (!sku) {
                Errors += "<li> You can not add a product without an Item Code</li>";
            }
            if (!name) {
                Errors += "<li> You can not add a product without a Name</li>";
            }
            if (!category) {
                Errors += "<li> You can not add a product without a Category</li>";
            }

            if (Errors != "") {
                cua({ text: Errors, type: 'danger' })
            }
            else {
                data.formData = { productName: name, productSKU: sku, affiliateID: affiliateId, categoryID: category, defaultImgName: defaultName }
                data.submit();
            }
        });

How do I assign the click event handler in the page load, and then trigger the actual event of the click later on?

Reason for this is it's causing errors where the button is unresponsive if an image is not uploaded, which I found to be caused by an event handling problem.

$(document).ready(function(){
    $("#finish").on('click', yourfunctionhere)
});

You can put your code in a seperate function, so if you want to turn it off, then on again you can do it with just 1 line of code.

$("#finish").on('click', yourfunctionhere)

To execute the function you can trigger the click (when the handler is on):

$("#finish").trigger('click');

(thanks @putvande for reminding)

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