jquery hover().addClass() 问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4358964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:07:41  来源:igfitidea点击:

jquery hover().addClass() problem

jqueryhover

提问by shin

http://jsfiddle.net/aBaw6/2/

http://jsfiddle.net/aBaw6/2/

This demo does not add class when you hover a list item.

当您将鼠标悬停在列表项时,此演示不会添加类。

What am I doing wrong here?

我在这里做错了什么?

$("li").hover(
  function () {
    $(this).addClass('hover);
  }, 
  function () {
    $(this).removeClass("hover");
  }
);

html

html

<ul>
    <li>Milk</li>
    <li>Bread</li>
    <li>Chips</li>
    <li>Socks</li>
</ul>

css

css

.hover{
    color:green;
    font-size: 20px;
}

Thanks in advance.

提前致谢。

回答by David says reinstate Monica

Your JavaScript was badly formed:

您的 JavaScript 格式错误:

$("li").hover(
  function () {
    $(this).addClass('hover);
  }, 
  function () {
    $(this).removeClass("hover");
  }
);

Should be:

应该:

$("li").hover(
  function () {
    $(this).addClass('hover');
  }, 
  function () {
    $(this).removeClass('hover');
  }
  );

If you click on the JS Lintbutton to the top of the screen it would've told you this (this isn't intended as a criticism, just a notefor your future use of JS Fiddle).

如果您单击JS Lint屏幕顶部的按钮,它会告诉您这一点(这不是批评,只是您将来使用 JS Fiddle的注释)。

回答by Oded

Your javascript syntax is incorrect

您的 javascript 语法不正确

$(this).addClass('hover);

Should be:

应该:

$(this).addClass('hover');

You forgot to terminate the string.

您忘记终止字符串。

It works just fine with this change.

这种变化效果很好。

回答by user113716

While others noted the missing quotation mark, I'd note that you should really be doing this with CSS instead of javascript:

虽然其他人注意到缺少引号,但我注意到您确实应该使用 CSS 而不是 javascript 来做到这一点:

http://jsfiddle.net/aBaw6/8/

http://jsfiddle.net/aBaw6/8/

li:hover{
    color:green;
    font-size: 20px;
}

IE6 doesn't support this on a <li>, but you could wrap the content with an <a>and style that if support is needed.

IE6不支持此上<li>,但你可以换用的内容<a>和风格,如果需要的支持。

If you did use javascript, you could reduce your code like this:

如果您确实使用了 javascript,则可以像这样减少代码:

http://jsfiddle.net/aBaw6/7/

http://jsfiddle.net/aBaw6/7/

$("li").hover( function (e) {
    $(this).toggleClass('hover', e.type === 'mouseenter');
});

回答by XMen

You Have Missed the quote '

你错过了报价'

   $("li").hover(
      function () {
        $(this).addClass('hover');
      },
      function () {
        $(this).removeClass("hover");
      }
    );