简体   繁体   中英

Can someone explain why this is passing in an object

I have something like the following..

$(document).ready(function() {
    $('#doReport').click(doReport);
});

function doReport(type) {
    if (type === undefined) {
        type = 'blah';
    }
    alert (type);
}

If I run doReport() from the console or standalone in the javascript with nothing in it, it will return 'blah' (as expected), and obviously if I call doReport('wibble'); it returns 'wibble' as you would expect.

But if I run it by clicking the element with ID doReport (utilising the bind I set up in .ready) it returns [object Object]

I don't understand why that would be the case.

The jQuery library passes your event handlers an "event" object. It will always be there. It's a "wrapped" or "fixed" version of the native browser object, making it somewhat easier to deal with.

Here is the documentation for such objects.

Also of note is the fact that jQuery will invoke your handler functions such that this refers to the DOM element for which the handler is being invoked.

Also also, as @Ericson578 points out in a good comment, jQuery allows additional parameters to be set up, which means that your handler may be passed additional parameters. That might be useful if you've got a single event handler function to be bound to different elements, but you'd like to qualify its behavior with some different flags or whatever based on the particulars of an element.

事件处理程序接收event对象作为参数。

This is because event handlers are triggered with an object (specifically, the event object) passed as the first argument.

This is the reason you see such syntax as

$('#doReport').click(function(e) {

If you want to call your function without any parameters, you'll need to create a wrapping function to do so:

$(document).ready(function() {
    $('#doReport').click(function() {
        doReport();
    });
});

When jQuery calls the function passed as parameter to click, it passed event object as the argument hence you are getting the alert as [object Object]. Check this:

http://api.jquery.com/click/

From JQuery - .click()

.click( handler(eventObject) ) handler(eventObject)A function to execute each time the event is triggered.

Your doReport() function is getting an event object.

wrap it with another function if you need to pass an argument to your function.

$(document).ready(function() {    
    $('#doReport').click(function(event){
        doReport('blah');
    });
});

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