我如何调用鼠标事件后点击事件在javascript中的同一函数

How do I call the mouse over event after click event on same function in javascript

本文关键字:事件 javascript 函数 何调用 调用 鼠标      更新时间:2023-09-26

我需要在JavaScript中单击鼠标后调用鼠标过事件,而不是jQuery,主要的事情是,在单击相同的函数事件后,函数是相同的它的新事件是鼠标悬停,有可能吗?

<a href="javascript:void(0);" id="digit" 
   onClick="javascript:return swapClass(val,val2);" 
   class="GetDivCount" onMouseOver="javascript:return swapClass(val,val2);"> 

那么这里需要在点击事件时首先调用swapClass()然后在点击事件之后调用onmouseover事件但是记住这个函数是参数化的

如果我理解正确的话,您希望在单击事件发生后等待观察onmouseover…要做到这一点,您必须摆脱内联事件处理程序。下面的例子应该可以工作。您必须区分浏览器是否可以使用addEventListener,因为旧版本的IE不支持它。

HTML:

<a href="javascript:void(0);" id="digit" class="GetDivCount">Hi</a>

JS:

var a = document.getElementById('digit');
if (a.addEventListener) {  // Most browsers....
    a.addEventListener('click', function test() {
        // Add code to determine val and val2
        swapClass(val,val2);
        a.removeEventListener('click', test, false); // Remove click listener
        a.addEventListener('mouseover', function() { // Add mouseover listener
            swapClass(val,val2);
        }, false);
    }, false);
} else { // Older versions of IE only support attachEvent :(
    a.attachEvent('onclick', function test() {
        // Add code to determine val and val2
        swapClass(val,val2);
        a.detachEvent('onclick', test);
        a.attachEvent('onmouseover', function() {
            swapClass(val,val2);
        });
    });
}

这里有两种可能的解决方案,使用jQuery和不使用jQuery: JSFiddle

没有:

var control = "";
var first  = document.getElementById("first");
var second = document.getElementById("second");
first.onclick = function(){
    control = true;
    alert("clicked | doSomething Here");
}
second.onmouseover = function(){
        if(control==true){
        alert("mouseovered after click | doSomething Here");
        //if you want again click and after mouseover evenet
        //you have to put here
        //control=""; 
    }
}

:

$("#first").on("click",function(){
    control = true;
    alert("cilcked | doSomething Here");
});
$("#second").on("mouseover",function(){
    if(control==true){
        alert("mouseovered | doSomething Here");
        //if you want again click and after mouseover evenet
        //you have to put here
        //control="";
    }
});