简体   繁体   中英

onmouseover doesn't work, function is not defined

I have an icon which needs to put the password_field that it is in to a textfield and vise versa.

<i class="password_icon fa fa-unlock" aria-hidden="true" onmouseover="mouseOverPassword()" onmouseout="mouseOutPassword()"></i>

But when I hover over the icon it says that:

Uncaught ReferenceError: mouseOutPassword is not defined
at HTMLElement.onmouseout ((index):1)

Even though they are in the .js file that I include:

function mouseOverPassword() {
    var obj = $("#passworldField");
    obj.type = "text";
}
function mouseOutPassword() {
    var obj = $("#passworldField");
    obj.type = "password";
}'

The functions are in a $(document).ready function. I can't really find out why it doesn't work. And yes, the .js is included on the page.

When the functions are scoped into another one, in your case in the $(document).ready they are not visible directly into the html. You need to bind them via Javascript. Get your element by id or name or something else and attach via that approach.

<i id="iEl" class="password_icon fa fa-unlock" aria-hidden="true"></i>

...

$('#iEl').on('mouseover', mouseOverPassword);
$('#iEl').on('mouseout', mouseOutPassword);

Your best way would be to move your functions out of the $(document).ready and define the mouseover event inside of your $(document).ready instead of doing it directly into your HTML.

$( "#element" ).mouseover(function() {
  mouseOverPassword() 
}

Same for mouseleave , check the jQuery docs here: https://api.jquery.com/mouseover/

Another thing would be to completely remove you $(document).ready and place your <script src="file.js"></script> to the bottom of your page, just before the </body> closing tag.

Some cases, you can't get a id tag for each element,

overall, works for me, is simpler, just move your function outside of document.ready {} scope.

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