【问题标题】:Toggling a background color change by clicking通过单击切换背景颜色更改
【发布时间】:2012-12-26 03:20:50
【问题描述】:

我正在快速做一个 jsFiddle 以了解更多关于 jQuery API 的信息,但一个 fiddle 并没有按我预期的方式工作。

jsFiddle:http://jsfiddle.net/7j5Fc/

HTML:

<div></div>

CSS:

div {
background:red;
height:100px;
width:150px;
}

JS:

$('div').click(
    function(){
        $(this).toggle(function(){
            $(this).style.background="blue";
        }
        //function(){
        //this.style.background = "orange";
        //}
        );
    }
);

奇怪的是,当我单击 div 时,它消失了,如果我取消注释注释行,草图根本不起作用。任何建议或信息表示赞赏。

【问题讨论】:

标签: javascript jquery jsfiddle


【解决方案1】:

您不需要将toggle() 包装在click() 方法中,只需使用:

$('div').toggle(
    function(){
        $(this).css('background-color', 'blue');
    },
    function(){
        $(this).css('background-color', 'red');
    });​

JS Fiddle demo.

另外,你正在混合使用 jQuery 和 JavaScript:

jQuery $(this) 对象没有style 方法;这需要使用css() 方法;这两种方法不可互换,因此您可以使用 css() 方法(上图),或者坚持使用纯 JavaScript:

this.style.backgroundColor = 'blue';

例如,或者从 jQuery 切换到纯 JavaScript:

$(this)[0].style.backgroundColor = 'blue';

或者:

$(this).get(0).style.backgroundColor = 'blue';

这两种方法本质上都是从允许使用本机 JavaScript 方法的 jQuery 对象中检索普通 DOM 节点/对象,但是,这意味着您不能在这些节点上使用 jQuery 方法/对象(当然,除非您将它们重新包装在 jQuery 对象中)。

当然,如果你只是想用jQuery来处理事件委托,你可以使用click()方法,再加上一个三元:

$('div').click(function(){
    this.style.backgroundColor = this.style.backgroundColor == 'blue' ? 'red' : 'blue';
});

JS Fiddle demo.

参考资料:

【讨论】:

  • 这是因为(我假设,因为没有评论),在我的初稿中,我没有看到将纯 JavaScript 链接到 jQuery 的混淆;在被否决的时候,这是应得的(但谢谢!)=D
  • 这是一个很好的答案。谢谢。 this.style.background='blue'; 也可以。注意到我忘记了function()s 之间的逗号二。
  • 不客气,很高兴能为您提供帮助!是的,原生 this 在 jQuery 方法中始终可用,这就是为什么您经常在方法函数中看到 $(this) 的原因(只是为了从可用的 DOM 节点创建一个 jQuery 对象)。
【解决方案2】:

您刚刚使用了错误的切换开关。有两个toggles:

toggle Event

toggle Effect

在您的代码中,执行了切换效果,它只是显示/隐藏一个元素。这就是为什么单击它时它会消失的原因。

【讨论】:

    猜你喜欢
    • 2018-09-19
    • 2021-04-27
    • 2016-04-05
    • 2022-11-22
    • 2017-01-15
    • 1970-01-01
    • 2021-03-28
    • 1970-01-01
    • 2019-09-01
    相关资源
    最近更新 更多