[英]Bypass onclick event and after excuting some code resume onclick
I have the below html button which have onclick event 我有下面的HTML按钮有onclick事件
<button onclick="alert('button');" type="button">Button</button>
and the following js: 和以下js:
$('button').on('click', function(){
alert('jquery');
});
After executing some js code by jQuery/Javascript, i want to continue with the button onclick handler eg: jquery alert first and than button alert. 在通过jQuery / Javascript执行一些js代码之后,我想继续使用按钮onclick处理程序,例如:首先是jquery Alert,然后是按钮alert。
i tried so many things like "remove attr and append it after executing my code and trigger click (it stuck in loop, we know why :) )" and "off" click. 我尝试了很多事情,例如“执行代码后删除attr并附加它并触发click(它陷入循环,我们知道为什么:))”和“ off” click。 but no luck. 但没有运气。
is it possible via jQuery/javascript? 是否可以通过jQuery / javascript?
any suggestion much appreciated 任何建议表示赞赏
Thanks 谢谢
Create a separate javascript function that contains what you want to do when the button is clicked (ie removing the onclick attribute and adding replacement code in its own function). 创建一个单独的javascript函数,其中包含单击按钮时要执行的操作(即,删除onclick属性并在其自己的函数中添加替换代码)。
Then call that function at the end of 然后在结尾处调用该函数
$('button').on('click', function(){
alert('jquery');
});
So you'll be left with something like this 所以你会留下这样的东西
function buttonFunction()
{
//Do stuff here
}
$('button').on('click', function()
{
alert('jquery');
buttonFunction();
});
<button type="button">Button</button>
A little bit tricky. 有点棘手。 http://jsfiddle.net/tarabyte/t4eAL/ http://jsfiddle.net/tarabyte/t4eAL/
$(function() {
var button = $('#button'),
onclick = button.attr('onclick'); //get onclick value;
onclick = new Function(onclick); //manually convert it to a function (unsafe)
button.attr('onclick', null); //clear onclick
button.click(function() { //bind your own handler
alert('jquery');
onclick.call(this); //call original function
})
});
Though there is a better way to pass params. 虽然有更好的方法来传递参数。 You can use data attributes. 您可以使用数据属性。
<button data-param="<%= paramValue %>"...
You can do it this way: 您可以这样操作:
http://jsfiddle.net/8a2FE/ http://jsfiddle.net/8a2FE/
<button type="button" data-jspval="anything">Button</button>
$('button').on('click', function () {
var $this = $(this), //store this so we only need to get it once
dataVal = $this.data('jspval'); //get the value from the data attribute
//this bit will fire from the second click and each additional click
if ($this.hasClass('fired')) {
alert('jquery'+ dataVal);
}
//this will fire on the first click only
else {
alert('button');
$this.addClass('fired'); //this is what will add the class to stop this bit running again
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.