函数句柄jQuery事件和参数? [英] function handle jQuery event and parameter?
问题描述
采取以下代码,
// Update button clicked
function updateEntity(e) {
e.preventDefault();
var name = $(this).attr("name");
...
// some stuff
...
}
$(document).on("click", ".updateEntity", updateEntity);
目前我有这个(去图)更新我按钮点击编辑的实体。现在,它的参数特别期待一个jQuery事件。但是,我希望能够在jQuery事件之外调用此函数(最终目标:最小化代码)。像这样,
Currently I have this for (go figure) updating an entity I've editted on button click. Now, its parameter is particularly expecting a jQuery event. However, I want to also be able to call this function (end goal: to minimize code) outside of a jQuery event. Like so,
// 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处理程序并像函数一样调用它并仍然正确使用它?如果我想实现这样的目标,这个目标是否现实还是应该以不同的方式构建?
Question: How would I go about calling updateEntity
or setting the function up, so that I can supply it to the click-event handler and call it like a function and still have it used correctly? Is this goal realistic or should I be structuring this differently if I want to achieve such a goal?
(包含它并不明显,我目前的问题是在功能上致电 updateEntity(e);
$(this)
成为窗口
而不是点击的链接。)
(Encase it is not obvious, my current problem is that on the function call updateEntity(e);
$(this)
becomes window
instead of the clicked link.)
推荐答案
使用 .call
设置这个
正确:
updateEntity.call(this, e);
了解此
的更多信息。
Learn more about this
.
这篇关于函数句柄jQuery事件和参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!