在Link onClick事件之前执行函数
Execute Function Before A Link onClick Event
我在一个无法访问源代码的页面上执行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>
相关文章:
- 如何做到这一点,使代码在不传递条件后执行函数
- javascript自执行函数-不同的语法
- JavaScript:只有当数组中的所有项都为true时才执行函数
- iFrame url更改时执行函数
- 为什么AngularJS在每个摘要循环上都执行函数
- 如何使用setInterval执行函数
- 当*ngFor以角度2结束时执行函数
- Ajax调用完成后如何执行函数
- 在显示引导弹出窗口之前执行函数
- 从自执行函数返回函数的Javascript性能命中率
- 在操作完成时执行函数
- jquery/js中的自执行函数
- 如何仅在完成对gap.client.youtube的请求.execute后执行函数
- 构造函数函数中的自执行函数的OO上下文/范围
- Javascript未使用=运算符执行函数
- AngularJS:如何按照预定义的顺序执行函数
- 在不使用隔离作用域的情况下执行函数的角度指令
- 如何在页面加载后执行函数是在 AngularJS 中完成的
- 完成页面加载后执行函数
- 如何在完成完全执行函数后触发循环