Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/408.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用原型触发事件_Javascript_Events_Prototypejs - Fatal编程技术网

Javascript 使用原型触发事件

Javascript 使用原型触发事件,javascript,events,prototypejs,Javascript,Events,Prototypejs,有人知道在原型中触发事件的方法吗,就像使用jQuery的触发器函数一样 我已经使用observe方法绑定了一个事件监听器,但是我也希望能够通过编程触发事件 提前感谢符合您的需要 我已经用过好几次了,效果很好。它允许您手动触发本机事件,如单击或悬停,如下所示: $('foo').simulate('click'); 最棒的是,所有附加的事件处理程序仍将被执行,就像您自己单击元素一样 对于自定义事件,您可以使用标准的prototype方法。我认为prototype中没有内置的方法,但您可以使用未经

有人知道在原型中触发事件的方法吗,就像使用jQuery的触发器函数一样

我已经使用observe方法绑定了一个事件监听器,但是我也希望能够通过编程触发事件

提前感谢

符合您的需要

我已经用过好几次了,效果很好。它允许您手动触发本机事件,如单击或悬停,如下所示:

$('foo').simulate('click');
最棒的是,所有附加的事件处理程序仍将被执行,就像您自己单击元素一样


对于自定义事件,您可以使用标准的prototype方法。

我认为prototype中没有内置的方法,但您可以使用未经测试的方法,但至少应该让您走上正确的方向:

Element.prototype.triggerEvent = function(eventName)
{
    if (document.createEvent)
    {
        var evt = document.createEvent('HTMLEvents');
        evt.initEvent(eventName, true, true);

        return this.dispatchEvent(evt);
    }

    if (this.fireEvent)
        return this.fireEvent('on' + eventName);
}

$('foo').triggerEvent('mouseover');

我觉得这篇文章很有帮助

它涵盖了在Firefox和IE中触发事件的方法

function fireEvent(element,event){
    if (document.createEventObject){
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else{
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}

这里的答案适用于普通事件,即由用户代理定义的事件,但对于自定义事件,您应该使用prototype的fire方法。e、 g

$('something').observe('my:custom', function() { alert('Custom'); });
.
.
$('something').fire('my:custom'); // This will cause the alert to display

太棒了!这对我帮助很大。谢谢:界面很好。但是,我希望这样。simulate方法以本机方式进入Prototype.js:这对于我们这些有插件许可问题的人来说并不管用——我最终在本机元素上调用了函数,因为Prototype太难了。它只支持HTML和鼠标事件。例如,您不能触发onchange事件,因为它是Form事件。但是,如果您为这些情况合并了Gregs脚本,那么它是一个非常好的工具。@JānisGruzis HTMLEvents包含“change”。看看我的答案。原型中有一个支持…Greg的答案对我来说很有用,但应该是$'foo'。triggerEvent'mouseover';而不是$foo.firevent'mouseover';抱歉,我是新来的,不知道如何引用或评论已经存在的答案。。。你是说$'foo'。触发事件'mouseover'?原型方式;很不错的!