You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

直接调用jQuery事件处理函数Generate时如何传递数据?

How to Pass Data When Directly Calling a jQuery Event Handler Function

Great question! I’ve run into this exact scenario before—when you’re used to relying on jQuery’s event.data for event-bound calls, direct function invocations can feel tricky at first. Let’s cover two solid approaches to solve this:


1. Simulate jQuery’s Event Object Structure

Since your Generate function expects an event parameter with a data property, you can directly pass a mock event object that matches this structure when calling the function manually:

var objKeyboard = {
    init: function( config ) {
        this.config = config;
        this.bindEvents();
        // Direct call with simulated event object
        this.Generate({ data: { idx: 2 } });
    },
    bindEvents: function() {
        this.config.selectedKey.on('change', { idx: 1 }, this.Generate);
    },
    Generate: function(event) {
        alert(event.data.idx); // Will alert 2 for the direct call, 1 for the event trigger
    }
};
objKeyboard.init({
    selectedKey: $("#selected_key_b"),
});

This works because you’re mirroring the exact structure jQuery passes to your handler when the event fires—no changes needed to your existing Generate logic.


If you want your Generate function to work seamlessly both as a jQuery event handler and as a standalone function, refactor it to accept optional direct parameters:

var objKeyboard = {
    init: function( config ) {
        this.config = config;
        this.bindEvents();
        // Direct call with explicit idx parameter
        this.Generate(null, 2);
    },
    bindEvents: function() {
        // Bind with event.data as before
        this.config.selectedKey.on('change', { idx: 1 }, this.Generate);
    },
    Generate: function(event, customIdx) {
        // Use customIdx if provided, otherwise fall back to event.data.idx
        var idx = customIdx || (event ? event.data.idx : 0);
        alert(idx); // Alerts 2 for direct call, 1 for event trigger
    }
};
objKeyboard.init({
    selectedKey: $("#selected_key_b"),
});

This approach makes your function more versatile—you can call it with or without the event context, and it’ll handle both cases gracefully.


Why Your Original Direct Call Didn’t Work

When you tried this.Generate({ idx: 2 }), your function was looking for event.data.idx, but your passed object only had event.idx. jQuery wraps your data in the data property of the event object when binding, so you need to match that structure (or refactor to avoid the dependency).

内容的提问来源于stack exchange,提问作者Gaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:52:37