繁体   English   中英

绕过onclick事件,执行某些代码后,恢复onclick

[英]Bypass onclick event and after excuting some code resume onclick

我有下面的HTML按钮有onclick事件

<button onclick="alert('button');" type="button">Button</button>

和以下js:

$('button').on('click', function(){
    alert('jquery');
});

在通过jQuery / Javascript执行一些js代码之后,我想继续使用按钮onclick处理程序,例如:首先是jquery Alert,然后是按钮alert。

我尝试了很多事情,例如“执行代码后删除attr并附加它并触发click(它陷入循环,我们知道为什么:))”和“ off” click。 但没有运气。

是否可以通过jQuery / javascript?

任何建议表示赞赏

谢谢

创建一个单独的javascript函数,其中包含单击按钮时要执行的操作(即,删除onclick属性并在其自己的函数中添加替换代码)。

然后在结尾处调用该函数

$('button').on('click', function(){
    alert('jquery');
});

所以你会留下这样的东西

function buttonFunction()
{
  //Do stuff here
}

$('button').on('click', function()
{
  alert('jquery');
  buttonFunction();
});

<button type="button">Button</button>

有点棘手。 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
    })
});

虽然有更好的方法来传递参数。 您可以使用数据属性。

<button data-param="<%= paramValue %>"...

您可以这样操作:

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.

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