Вопрос

Here is a simple jquery code:

$(document).ready(function() {


/*$(function() {
    // Sets the value of the submit_button_type field if the 'Submit & Add
    // Another button is clicked.
    $('#submit-id-submit_and_add').click(function() {
        $('#id_submit_button_type').val('submit_and_add');
    });
}); */

$('#submit-id-submit_and_add').click(function() {
        $('#id_submit_button_type').val('submit_and_add');
    });
}

what is the difference between the above two? In the first, I have enclosed the click handler inside the function In the second, I have defined it globally.

will the first function gets run twice once, upon the document ready and other, when button is clicked

The second way of defining globally, how does that work. will it only be evaluated when the click happens

suppose my html is

<input id="id_submit_button_type" name="submit_button_type" type="hidden" />
<input type="submit" name="submit_and_add" value="Save &amp; Add Another" id="submit-id-submit_and_add"/>

I want to attach onclick in the input element something like

<input type="submit" name="submit_and_add" value="Save &amp; Add Another" id="submit-id-submit_and_add" onclick=somefunction/>

The somefunction will set the value for the input element here. how would I define somefunction in my js file, so that I could call it here. should that be wrapped inside $(document).ready(function() { } such as

var somefunction=$('#submit-id-submit_and_add').click(function() {
            $('#id_submit_button_type').val('submit_and_add');
        });
    }

I am a beginner in Jquery. so these doubts could be silly. Thanks for your patience

Это было полезно?

Решение

$(function() {
    <code>
});

is short for:

$(document).ready(function() {
    <code>
});

So the first version says to bind the handler after the document is ready. But since all the code is inside another document ready handler, it's already waiting for that event, so the extra wrapper has no effect. So the two versions are equivalent.

If you want a named function that does what the click handler does, you can do:

function somefunction() {
    $('#id_submit_button_type').val('submit_and_add');
}

$(document).ready(function() {
    $('#submit-id-submit_and_add').click(somefunction);
});
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top