简体   繁体   中英

Simple Function Not working in Javascript

I've been messing with this function and got it to work when I had it set up like this:

$(document).ready(function () {
            var num1 = document.getElementsByClassName("top")[0];

            num1.onmouseover = (function(){
                var changeIt = document.getElementsByClassName("topb")[0];
                if (changeIt.style.visibility === "hidden") {
                    changeIt.style.visibility = "visible";
                }else {
                changeIt.style.visibility = "hidden";

My problem is that I'm currently trying to make it a reusable function, for multiple variables. When I try and set it up like this:

$(document).ready(function () {

            var num1 = document.getElementsByClassName("top")[0];
            var num1b = document.getElementsByClassName("topb")[0];

            function myFunc(x){
                if(x.style.visibility === "hidden") {
                    x.style.visibility = "visible";
                }else {
                    x.style.visibility = "hidden";
                }};

            num1.onmouseover= myFunc(num1b);

It won't work. I'm sure it's some syntax or scope issue? Not quite sure I've been researching it and can pin it down). Does anyone out there have a suggestion? Thank you so much in advance. PS my CSS and HTML are fine, seeing that I have had them working with the previous function set up.

The problem is that you are assigning the result of the function to the mouseover event, not the function itself. Since it doesn't return anything, it is being assigned to undefined and therefore having no effect.

Since your function is within the scope that has access to the num1b variable, you do not need to pass it as a parameter.

Try this instead:

function myFunc(){
  if(num1b.style.visibility === "hidden") {
    num1b.style.visibility = "visible";
  }else {
    num1b.style.visibility = "hidden";
  }
};

num1.onmouseover = myFunc;//assign the FUNCTION not the result by not including parenthesis

or, to make use of jQuery to reduce code, you could simply do this:

$(".top").mouseover(function () {
  $(".topb").toggle();
});

mouseover will cause this to fire every time the mouse moves one pixel over the element, so this could result in rapid flashing, you may want to use the mouseenter and mouseleave to have better control over this behavior.

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