通过单击切换背景颜色更改 [英] Toggling a background color change by clicking

查看:102
本文介绍了通过单击切换背景颜色更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很快就做了一个jsFiddle来了解有关jQuery API的更多信息,而小提琴并没有按照我期望的方式工作.

I was quickly doing a jsFiddle to learn more about the jQuery API, and a fiddle isn't working the way I expected.

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

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消失了,如果我取消注释注释行,则草图根本不起作用.任何建议或信息表示赞赏.

Strangely, the div disappears when I click it, and if I uncomment the commented lines the sketch doesn't work at all. Any suggestions or info appreciated.

推荐答案

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

You don't need to wrap the toggle() in the click() method, just use:

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

JS小提琴演示.

此外,您正在混合使用jQuery和JavaScript:

Also, you're mixing jQuery and JavaScript:

jQuery $(this)对象没有style方法;需要使用css()方法;这两种方法不可互换,因此您可以使用css()方法(如上所述),也可以坚持使用普通JavaScript:

The jQuery $(this) object has no style method; that requires the use of the css() method; the two approaches are not interchangeable, so you could either use the css() approach (above), or stick with plain-JavaScript:

this.style.backgroundColor = 'blue';

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

For example, or switch from jQuery to plain JavaScript:

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

或者:

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

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

Both of these approaches essentially retrieve the plain DOM node/object from the jQuery object which allows native JavaScript methods to be used, it does, however, mean that you can't then use jQuery methods on those node(s)/object(s) (unless you re-wrap them in a jQuery object, of course).

当然,如果您只想使用jQuery处理事件委托,则可以使用click()方法,并结合三元方法:

Of course, if you just want to use jQuery to handle the event-delegation, you could use the click() method, coupled with a ternary:

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

JS小提琴演示.

参考:

这篇关于通过单击切换背景颜色更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆