函数句柄jQuery事件和参数?
拿下面的代码,
// Update button clicked function updateEntity(e) { e.preventDefault(); var name = $(this).attr("name"); ... // some stuff ... } $(document).on("click", ".updateEntity", updateEntity);
目前我有这个(去图)更新我按钮点击编辑的实体。 现在,它的参数特别期待一个jQuery事件。 但是,我希望能够在jQuery事件之外调用此函数(最终目标:最小化代码)。 像这样,
// Do an update but then redirect to prevent adding the same estimate twice. function createEstimate(e) { updateEntity(e); var link = $(this).attr("href"); window.location.href = link; } $(document).on("click", ".createEntity", createEstimate);
问题:如何调用updateEntity
或设置函数,以便我可以将它提供给click-event处理程序并像函数一样调用它并仍然正确使用它? 这个目标是否现实,或者如果我想实现这样的目标,我应该以不同的方式构建这个目标吗?
(包含它并不明显,我目前的问题是在函数调用updateEntity(e);
$(this)
成为window
而不是单击的链接。)
使用.call
正确设置:
updateEntity.call(this, e);
了解更多相关信息 。