简体   繁体   中英

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())

    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.

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...

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.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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