为什么这个悬停切换jQuery不工作

Why is this hover toggle jQuery not working?

本文关键字:jQuery 工作 悬停 为什么      更新时间:2023-09-26

我有单独的jQuery函数"mouseenter"answers"mouseleave"工作良好:

$('#imgPostTravel').mouseenter(function () {
    $('#imgPostTravel').addClass('popout_image');
    $('#imgPostTravel').addClass('shadow');
});
$('#imgPostTravel').mouseleave(function () {
    $('#imgPostTravel').removeClass('popout_image');
    $('#imgPostTravel').removeClass('shadow');
});

…但我希望将其整合为一个"悬停"切换操作。

我首先想确保它确实有效,所以在jsfiddle上尝试了以下操作:

$( "ptVerbiage" ).hover(function() {
    $(this).val('yep!');
}, function() {
    $(this).val('nope!');
});

除了设置"val"的值(改变"禁用"属性,改变颜色,背景色等)之外,我还尝试了一些事情,但他们都没有做任何事情。这是错误的方式悬停/切换,或者什么错了?

您忘记使用标签来引用ID。另外,您的目标元素是h2,它没有.val()方法,因为它不是表单(文本)输入。你必须用.text()代替。

这部分代码应该是这样的(jsFiddle):

$("#ptVerbiage").hover(function() {
    $(this).text('yep!');
}, function() {
    $(this).text('nope!');
});

你好像少了一个#

$("ptVerbiage") => $("#ptVerbiage")

not .val() but .text();正如.val用于输入

应该像这样

$( "#ptVerbiage" ).hover(function() {
  $(this).text('yep!');
}, function() {
  $(this).text('nope!');
});
http://jsfiddle.net/n9sq7x8y/4/

根据大家的建议,以下是可行的:

$( "#imgPostTravel" ).hover(function() {
    $(this).addClass('popout_image');
    $(this).addClass('shadow');
}, function() {
    $(this).removeClass('popout_image');
    $(this).removeClass('shadow');
});