开发者

jQuery: Name a generic function so I can call it after ajax event

开发者 https://www.devze.com 2023-01-28 16:29 出处:网络
I have the following code which sets up some custom form elements on the page load and then updates them if the user clicks on them:

I have the following code which sets up some custom form elements on the page load and then updates them if the user clicks on them:

// Setup Function
$(function () {
    $('form.vote_ballot > input:checked').prev().addClass('selected');
});

// Interaction Function
$(document).ready(function() {
    $('form.vote_ballot > label').click(function() {
        $(this).siblings().removeClass("selected").end()
            .addClass("selected");
    });
    $('form.vote_ballot').change(function() {
        $('form.vote_ballot').submit();
    });
});

This basically allows a user to give a "thumbs-up" or "thumbs-down" vote. The code works as expected when a user is editing an existing vote, but when they create a new vote an ajax request is processed and the initial setup function needs to be called again. The setup function should only be called once (which is why it's outside the document.ready block). The interaction portion in the document开发者_如何学运维.ready block works fine before and after the ajax event.

I'm not very skilled with jQuery, and I haven't been able to figure out how to take the setup function and give it a name so I can call it again after the ajax event.

Any help?


This code:

$(function () {

and this:

$(document).ready(function() {

do exactly the same. So you can process everything on one block, like this:

$(function () {
    var setupFunction = function() {
      $('form.vote_ballot > input:checked').prev().addClass('selected');
    }

    // Setup Function
    setupFunction();

    // Interaction Function
    $('form.vote_ballot > label').click(function() {
        $(this).siblings().removeClass("selected").end()
            .addClass("selected");
    });
    $('form.vote_ballot').change(function() {
        $('form.vote_ballot').submit();
    });

    // example ajax call:
    $.ajax({ ...
      success: function () {
        ...
        addSelected(); // call from here for example
        ...
      }
    });
});

As you see I wrapped some part of code to a function (I called it setupFunction), and I can call it anywhere inside $(function () { ... }); block

0

精彩评论

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