简体   繁体   English

为什么在页面加载时调用javascript onmouseover函数?

[英]why is javascript onmouseover functions is getting called on page load?

I have a html page with a link and onMouseOver of that link I'm calling return escape(showToolTip()) 我有一个带有链接的html页面,该链接的onMouseOver我正在调用return escape(showToolTip())

    function showToolTip(){
alert(document.getElementById('toggleFlag'));
        var text;
        alert(document.getElementById('toggleFlag').value);
        if(document.getElementById('toggleFlag').value == false){
            text = 'hide';
            alert('hide');
        }else{
            text = 'show';      
            alert('show');
        }

This function is getting called on page load and when I mouse over I get show. 在页面加载时会调用此函数,当我将鼠标悬停在上面时会显示。 When I mouse out and mouseover again it shows up as 'show' but never calls the function. 当我将鼠标移出并再次悬停在鼠标上时,它显示为“ show”,但从未调用该函数。

Where am I doing wrong? 我在哪里做错了?

My guess is that when you're setting your event handler, you're including the parenthesis on the method you wish to call. 我的猜测是,在设置事件处理程序时,将在要调用的方法中包括括号。

Such as: 如:

onMouseOver = showTooltip()

This causes the event to fire immediately and the handler to only be given the result of the method that already executed. 这将导致事件立即触发,并且仅向处理程序提供已执行方法的结果。

If this is the case you'll want to change your event hander by removing the parenthesis. 如果是这种情况,您将需要通过删除括号来更改事件处理程序。

onMouseOver = showTooltip

As pointed out in the comments below, this isn't accounting for declerative event handling such as: 如以下评论中所指出的,这不考虑诸如此类的决定性事件处理:

<div onmouseover="foo()">

which will not fire on page load. 不会在页面加载时触发。

Again, per my comment, I have no idea what the rest of your implementation looks like, but you're never actually toggling the value of 'toggleValue' in your method... 再次,根据我的评论,我不知道其余的实现是什么样的,但是您实际上从未在方法中切换“ toggleValue”的值...

function showToolTip(){    
     var text;             
     if(document.getElementById('toggleFlag').value == false){       
          // TOGGLE TO TRUE      
          document.getElementById('toggleFlag').value = true;
          text = 'hide';             
          alert('hide');         
     }
     else {            
          // TOGGLE TO FALSE
          document.getElementById('toggleFlag').value = false; 
          text = 'show';                   
          alert('show');         
     } 
}

Put quotes around your true and false. 在您的对与错旁加上引号。 You are comparing a string to a js bool rather than the value inside the element. 您正在将字符串与js bool进行比较,而不是将元素内部的值进行比较。

if(document.getElementById('toggleFlag').value == "false"){
            text = 'hide';
            alert('hide');
        }else{
            text = 'show';      
            alert('show');
        }

A fiddle of what I'm seeing is here: http://jsfiddle.net/k7mJX/ 我在这里看到的小提琴是: http : //jsfiddle.net/k7mJX/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM