简体   繁体   English

你可以绑定.click(),以便它在onclick之前触发吗?

[英]can you bind .click() so that it fires prior to onclick?

I'm writing jQuery for an app that's being build in JSF. 我正在为一个用JSF构建的应用程序编写jQuery。 The JSF components are using a lot of their own JS for doing whatever JSF does and they use a lot of onclick attributes to handle it all. JSF组件使用了很多自己的JS来执行JSF所做的任何事情,并且他们使用大量的onclick属性来处理它们。

Is there valid/proper way to bind your own click event to an element and ensure that your event fires prior to the default onclick event? 是否有有效/正确的方法将您自己的click事件绑定到元素并确保您的事件在默认的onclick事件之前触发? It appears that by default a jQuery click function is fired after any inline onclick function calls. 看来默认情况下,在任何内联onclick函数调用之后会触发jQuery单击函数。

In jQuery events are triggered strictly in the order in which they were registered. 在jQuery中,事件严格按照它们的注册顺序触发。

You can circumvent any inline DOM0 onclick style handlers by iterating over the whole DOM, removing those onclick properties, and then registering your own handler which then invokes the originally defined function. 您可以通过迭代整个DOM,删除那些onclick属性,然后注册自己的处理程序然后调用最初定义的函数来规避任何内联DOM0 onclick样式处理程序。

Something like: 就像是:

$('[onclick]').each(function() {
    var handler = $(this).prop('onclick');
    $(this).removeProp('onclick');
    $(this).click(handler);
});

See http://jsfiddle.net/alnitak/2SCTK/ http://jsfiddle.net/alnitak/2SCTK/

So, register your own handlers first with jQuery, then invoke the code above to remove the original inline onclick handlers and re-register them as if jQuery had added them. 因此,首先使用jQuery注册您自己的处理程序,然后调用上面的代码删除原始的内联onclick处理程序并重新注册它们,就像jQuery添加它们一样。

EDIT code simplified to just use the original function - jQuery will ensure that the function is invoked with the right context. EDIT代码简化为仅使用原始函数--jQuery将确保使用正确的上下文调用该函数。 Previous code which explicitly set the context to window was incorrect. 显式将上下文设置为window先前代码不正确。

You can remove the onClick event from the DOM element, and then rebind it using jQuery. 您可以从DOM元素中删除onClick事件,然后使用jQuery重新绑定它。

<div id="click" onclick="alert('DOM')">CLICK ME</div>

$('#click').click(function(){
    alert('jQuery');
});

var clickFunc = $('#click').prop('onclick');
$('#click').removeProp('onclick');
$('#click').click(clickFunc);

Events are called in the order they are bound, so the only way to call your function first, is to unbind, and then rebind the original function. 事件按它们绑定的顺序调用,因此首先调用函数的唯一方法是取消绑定,然后重新绑定原始函数。

Demo: http://jsfiddle.net/wYd5t/2/ 演示: http//jsfiddle.net/wYd5t/2/

There is no way to mandate event firing order for the same listener on the same element. 无法在同一元素上为同一个侦听器强制执行事件触发顺序。 Every browser is free to fire the events in any order it chooses. 每个浏览器都可以按照它选择的任何顺序自由触发事件。

你可以在元素上使用onmousedown

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM