Call function with parameter in jQuery

When I click on the control with the identifier Button1, it calls a function called getMakes, I want to pass a parameter to it. In this case, the identifier of the control that will receive the data. What am I doing wrong?

$(function () {

        $('#Button1').click(getMakes("'#output'"))
        $('#buttonClear').click(function () {
            $('#output').html('');
        });
});
function getMakes(myVar) {   
$.ajax({
    type: "POST",
    url: "WebService.asmx/dbAccess2",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
        var response = msg.d;
        $.each(response, function (index, value) {
            $(myVar).append(new Option(value, index));
        });
    },
    failure: function (msg) {
        alert('failure');
    }
});

}

+3
source share
3 answers

OJ and Jacob have the right solution, but they did not explain why. Your code

$('#Button1').click(getMakes("'#output'"))

getMakes . ( , ). , , click . , , , . - , .

, . , .

+5

:

$('#Button1').click(function() {
    getMakes('#output');
});
+4

Instead

$('#Button1').click(getMakes("'#output'"))

.. (note that there is no semicolon at the end) .. Do this:

$('#Button1').click(function() { getMakes("'#output'"); });
0
source

Source: https://habr.com/ru/post/1775122/


All Articles