在onClick事件之前执行函数

3

我正在对一个没有源代码访问权限的页面进行DOM操作。我想要阻止链接的onClick处理程序执行,添加我的自定义函数,然后允许原始的onClick函数正常执行。以下是页面代码示例:

<a href="#" onclick="myAjaxFunction('param1, param2');return false;" name="buyLink" id="buyLink" >Buy Now</a>

我已经想出以下代码框架:

jQuery('#buyLink').click(function(event){
    event.preventDefault();
    my2ndFunction(); // alert(‘I ran’);
    //execute myAjaxFunction() here
});

我有两个挑战:

1)当我使用Alert()代码进行测试时,警报出现,但原始函数仍然运行(preventDefualt似乎无效)。

2)如何调用具有正确动态参数值的原始函数?(也许以某种方式使用“self”?)

2个回答

5

首先,备份原始的 onclick 处理程序。 然后,从元素中删除它。 最后,创建自己的处理程序。 在您的处理程序中,调用原始函数。

var orig_onclick = $('#buyLink').prop('onclick');
$('#buyLink').removeProp('onclick');

$('#buyLink').click(function(e){
    // Do your own code
    my2ndFunction();

    // Call the original function, with the correct context.
    return orig_onclick.call(this, e.originalEvent);
});

DEMO: http://jsfiddle.net/qbz7wn9o/


那在我的环境中应用成功了,但我无法让 jsfiddle 运行任何内容。控制台输出应该出现在页面上还是我的 FireBug 控制台上(两者都没有出现)? - user1754738
它应该出现在浏览器的控制台中。我不使用Firebug。 - gen_Eric

0

以下是一种不需要存储onclick事件即可实现的方法。

var button = document.querySelector("button");

// add your listener
button.addEventListener("click", function(event) {
  alert("listener action");
  // calling stopImmediatePropagation here will prevent the inline action...
  // ...from executing once it's moved to afterwards in the queue
  //event.stopImmediatePropagation();
});

// move the inline listener to execute after yours
if (button.onclick !== null) {
  button.addEventListener("click", button.onclick);
  button.onclick = null;
}
<button onclick="alert('inline action');">click me</button>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接