在我的应用程序中,我有很多 anchor 标记和按钮,其中大部分都有通过元素上的 onclick 调用的事件。
我想要的是在调用任何其他函数之前调用一个函数。
html
<input type="button" value="add" onclick="add()">
<input type="button" value="sub" onclick="sub()">
<input type="button" value="div" onclick="div()">
js
function add(){
alert("add");
}
function sub(){
alert("sub");
}
function div(){
alert("div");
}
$(document).on("click","input[type=button]",function(){
alert("bye");
});
这是 fiddle fiddle
我以为是
$(document).on("click","input[type=button]",function(){
....
});
将首先被调用,以便我可以在之前处理一些东西
function show(){
alert("hi");
}
被称为 ,但事实并非如此。 应该怎么做才能做到这一点。
我想在所有 anchor 标记和按钮上调用 a 函数,甚至在
之前onclick="show()"
Update
我已经更新了 fiddle
附言
每个元素都有自己的调用函数,但是 $(document) 中的函数与我想调用的所有元素过滤的函数相同。 我有一些建议,为什么不创建一个具有 $(document) 逻辑的函数,并在元素调用的所有函数上调用它,即 add()、sub()、div()。 但答案是不,我不能,因为它只是一个演示,我的真实应用程序很大,无法计算每个函数并调用其他函数。这就是为什么我想要一个替代方案。
最佳答案
onclick attr 将首先被调用,因为它直接事件在元素上 就是这样,但是您可以对函数本身的事件进行一些操作 这里有一种方法可以实现你想要的,但正如我在评论中所说的那样有点困惑:
<!DOCTYPE HTML>
<html ng-app>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js" type="text/javascript"></script>
<title></title>
</head>
<body>
<a id="click" onclick="show(this);">c</a>
<script type="text/javascript">
function show(t){
events = $._data(document, 'events');
events.click[0].handler();
alert("hi");
$(document).off("click","#click");
}
$(document).on("click","#click",function(){
alert("bye");
});
</script>
</body>
</html>
基本上,您在这里所做的是在执行 onclick 函数逻辑之前调用其他处理程序,换句话说,您从 onclick 调用其他处理程序此代码有效,但您应该对要查找和运行的事件使用一些过滤器每个事件的循环
另一种方法是保存 onclick 值并将其附加到您自己的事件中,然后删除 onclick 属性值:
http://jsfiddle.net/qmbcgz5y/11/
function add(){
alert("add");
}
function sub(){
alert("sub");
}
function div(){
alert("div");
}
function firstfunction(){alert('first func');}
$(function(){
$("input[type=button]").each(function(){
var onclickfunc = $(this).attr('onclick');
$(this).attr('onclick','');
$(this).on('click',function(){
firstfunction();
eval(onclickfunc);
});
});
});
关于javascript - 为什么 click 事件首先由元素上的 onclick 触发,而不是 $(document).on ('click' )?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30023172/