问题描述
单击Cancel
按钮时,我将调用两个函数,一个Java脚本和一个Jquery函数.
Java脚本函数在Jquery函数之前执行,我希望完全相反.
这是我的HTML代码
I am calling two function one Java script and one Jquery function on click of Cancel
button.
The java script function get executed before Jquery function and I want the exactly opposite.
Here is my HTML code
<button type="button" class="noWarning" id="cancelButton"
onclick="javascript: showMessage('cancelButton', 'Cancelling...'); disableButtons(); submitForm('${cancelDataRequestFormUrl}');">
Cancel</button>
Jquery函数
$(".noWarning").click(function()
{
needToConfirm = false;
alert("NeedToConfirm : " + needToConfirm);
});
showMessage('cancelButton', 'Cancelling...');
在$(".noWarning").click(function())
之前执行,所以如何更改执行顺序?
我用另一个按钮尝试过
showMessage('cancelButton', 'Cancelling...');
get executed before $(".noWarning").click(function())
so how can I change the execution order ?
I tried same with another button
<button type="button" class="noWarning" id="saveButton"
onclick="javascript: submitDataRequest('saveButton', 'Saving...', 'newDataRequestForm', '${saveDataRequestFormUrl}', '${successSaveDataRequestFormUrl}');">
Save as Draft</button>
其正常工作的Jquery
函数在onClick
函数之前被调用.
这带来了更多的混乱.
And its working fine Jquery
function is getting called before onClick
functions.
Which puts more confusion.
推荐答案
在JavaScript中,回调和事件处理程序应按绑定的顺序执行,并且无法更改该顺序. onclick
属性中的代码将在创建元素后直接绑定,因此将是第一个执行的代码.
In JavaScript, callbacks and event handlers should be executed in the order they were bound, and there is no way to alter that order. The code in the onclick
attribute will be bound directly after creation of the element, and will thus be the first to be executed.
防止这种情况的唯一方法是通过使用jQuery的在源或客户端中删除属性. .removeAttr
,如该测试案例所示.
The only way to prevent this is to remove the attribute, either in the source or client-side by using jQuery's .removeAttr
, as seen in this test case.
然后可以按照希望执行的顺序将回调与jQuery绑定:
You can then bind the callbacks with jQuery in the order you want them to be executed:
$(".noWarning").click(function(){
needToConfirm = false;
alert("NeedToConfirm : " + needToConfirm);
});
$("#cancelButton").click(function(){
showMessage('cancelButton', 'Cancelling...');
disableButtons();
submitForm('${cancelDataRequestFormUrl}');
});
请注意,使用onclick
属性被认为是一种不良做法,这种做法可追溯到90年代,应避免使用. JavaScript应该与HTML分开,最好尽可能放在单独的文件中.
Please note that the usage of the onclick
attribute is considered a bad practice that belongs back in the 90s and should be avoided. JavaScript should be separated from the HTML and best be put in a separate file if possible.
这篇关于如何确定Javascript和Jquery函数的执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!