0

我有一个期望点击事件对象作为参数的函数。例如

toggle: function (e) {
//does all the required work and then calls cancelEvent

this.cancelEvent(e);//IMPORTANT TO HANDLE LOCAL ANCHORS
    },


cancelEvent:function(e) {
    if (!e) e = window.event;
        if (e.preventDefault) {
        e.preventDefault();
                  } else {
            e.returnValue = false;
                  }
    },

我需要在页面加载时调用切换功能。

我尝试在不传递事件参数的情况下调用它。但是,这样做会破坏预期的功能,并且一切都变得不可编辑。

无论如何我可以获取当前事件对象并将其传递给函数吗?

还是我应该将加载事件也附加到事件侦听器中?

请让我知道出路是什么?

感谢您的时间 :)

4

2 回答 2

1

No need to even use jQuery. JavaScript in the browser includes a native Event object. So you should be able to call your toggle function directly (assuming you have access to the scope it was defined in) like this...

var fakeEvent = new Event('click');
toggle(fakeEvent);

Be sure to test thoroughly. If your code is relying on certain property values that the event would only have if it were triggered from a real user click then this may not work for you.

A better option would be to refactor so that the functionality that is shared by both page load and click is factored into a new function which can be called from both the click event handler function and the page load logic.

于 2013-01-05T16:03:12.563 回答
0

是的,您可以使用 jQuery 创建事件:

var e = $.Event('click');
$element.trigger(e); // Triggers click event on element

这是关于$.Event. 通过以下方式使用 jQuery 触发点击事件也会为您创建一个事件对象:

$element.click();
于 2013-01-05T09:54:22.407 回答