在链接onClick事件之前执行功能

时间:2014-08-12 19:17:19

标签: javascript jquery

我在无法访问源代码的页面上执行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)如何使用正确的动态参数值调用原始函数? (也许以某种方式使用“自我”?)

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分: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>

相关问题