在javascript中定义事件后执行函数的顺序

时间:2016-12-20 16:28:07

标签: javascript events

在阅读之前,我已经阅读了这个帖子:Order of execution of functions bound to an event in Javascript但它没有帮助。其实, 我有一个匿名函数,定义如下:

<input type="button" name="blablabla" value="Send" onclick="javascript:blablabla">

所以,这个函数在一个按钮上,用于验证表单。如您所见,它是一个匿名函数,我对此代码没有任何访问权限。单击它时会启动此功能。好的,我已经明白了

但是,这个功能并不完全,我想用自己的检查逻辑添加自己的功能。所以我先想要我的支票,然后调用匿名函数。这是我的代码:

function check() {
  console.log("debut de check");
  var participant = document.getElementById("new_participant_name");
  var participant1 = document.getElementById("new_participant2_name");
  var participant2 = document.getElementById("new_participant3_name");
  participant = participant.value;
  participant1 = participant1.value;
  participant2 = participant2.value;

  var trois_participants = (participant2) ? true : false;
  if (!participant1 || !participant)
  {
    console.log("pas de participant1 ou participant, sert à rien de gérer la suite");
    //if the script come here, I want to stop processing, and don't want to call the anonymous function.
    return ;
  }
}
window.onload = function()
{
  document.getElementById("InsertButton").addEventListener('click', function () {
check();
})};

所以,我想在匿名函数之前调用我的函数(check),但是,使用相同的事件。我不知道我是否完全理解......谢谢你们。

编辑:对不起伙计们,我的代码之前有错误,是的,代码是内联的,明天我会尝试你所有的解决方案,谢谢你们

3 个答案:

答案 0 :(得分:3)

如果(并且仅当)使用内联onclick="..."处理程序附加现有处理程序,您可以获取其值,然后覆盖它:

window.onload = function() {
    var el = document.getElementById('InsertButton');
    var old_click = el.onclick;
    el.onclick = undefined;
    el.addEventListener('click', function() {
        check();
        old_click(this);
    });
}

答案 1 :(得分:2)

为什么不创建自己的处理程序?

Element.prototype.myEventListener=function(name,func){
 this.addEventListener(name,function(){
   if(!check()){return;}
   func();
 });
 };

现在你可以做到:

document.body.myEventListener("click",function(){
alert("t");
});

将始终在注册的处理程序之前调用Check。 注意,要阻止呼叫,请检查必须返回false:

function check(){
 return false;//no custom eventlistener fires
 return true;//all will fire
 }

答案 2 :(得分:0)

使用useCapture flag,这样您就可以在事件向下移动时拦截事件。
此时您可以执行检查,如果失败,您可以致电stopPropagation on the event,以防止它到达与其冒泡阶段相关联的处理程序。

另外,从本质上讲,事件在管理执行顺序方面非常糟糕。一般来说,它们取决于听众的注册顺序。

// code over which you have no control and can't change
var btn = document.getElementById("greeter");
btn.addEventListener("click", function() {
  console.log("hello");
})


// code you can add later
function check() {
  return Math.random() > 0.5;
}

window.addEventListener("click", function(e) {
  var greeter = document.getElementById("greeter");
  if (e.target === greeter && !check()) {
    e.stopPropagation();
  }
}, true)
<button id="greeter">hello world</button>

相关问题