如何用另一个onclick事件触发包装在一个事件中的代码

How to trigger code wrapped in one event with another onclick event

本文关键字:事件 一个 代码 另一个 何用 onclick 包装      更新时间:2023-09-26

将此代码包装在HOVER Event…

$("#div_ID").hover(function() {
  // perform stuff here...
}
);

当我使用ONCLICK事件点击链接时,我想触发上述事件…

$("anchor_ID").click (function() {
 $("div_ID").trigger('hover'); // Not sure if this is even correct
}
);

但它不起作用。我怎样才能做到这一点呢?这可能吗?仅在FF v16, IE8和GC v23上使用JQuery

这个怎么样:

var dosomething = function() {
    // perform the stuff here
}
$('#div_ID').hover(dosomething);
$('anchor_ID').click(dosomething);

但是如果您设置使用.trigger,您的问题可能是您忘记在div_ID之前包含#。并将hover更改为mouseenter(在jQuery中的"hover"功能只是"mouseenter"的快捷方式-信用到@FabrícioMatté捕捉),即:

//change this:
$('div_ID').trigger('hover');
//To this:
$('#div_ID').trigger('mouseenter');

同样可能适用于anchor_ID,但我不知道,除非你发布你的HTML。

Update:另一个来自@FabrícioMatté的建议:dosomething内部的this关键字在您如上所示调用它时可能会有点混乱,所以要注意它。this关键字的工作方式与使用.trigger不同,所以它只是一个提示....

hover不是一个事件,所以你不能trigger它。.hover()只是附加mouseentermouseleave处理程序的简写。

$("#anchor_ID").click(function() {
    $("#div_ID").trigger('mouseenter');
});

小提琴

注意,当传递单个参数时,.hover将把函数附加到mouseentermouseleave上,因此您可以触发它们中的任何一个。
如果您打算仅在用户将鼠标移动到div上方时执行处理程序,我建议将处理程序附加mouseenter而不是hover