在Link onClick事件之前执行函数

Execute Function Before A Link onClick Event

本文关键字:执行 函数 事件 Link onClick      更新时间:2023-09-26

我在一个无法访问源代码的页面上执行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()代码来测试这一点时,警报出现,但原始功能无论如何都运行(preventdefault似乎不起作用)。

2)如何使用正确的动态参数值调用原始函数?

首先,备份原始的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);
});

演示:http://jsfiddle.net/qbz7wn9o/

这里有一种不需要存储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>