Toggling a background color change by clicking

拈花ヽ惹草 提交于 2019-12-08 07:35:29

问题


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/

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";
        //}
        );
    }
);

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.


回答1:


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 Fiddle demo.

Also, you're mixing jQuery and 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';

For example, or switch from jQuery to plain JavaScript:

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

Or:

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

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).

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 Fiddle demo.

References:

  • click().
  • css().
  • get().
  • toggle().



回答2:


You just used wrong toggle. There are two toggles:

toggle Event

and

toggle Effect

In your code, toggle Effect were executed which simply show/hide an element. That is why it disappears when you click it.



来源:https://stackoverflow.com/questions/14033265/toggling-a-background-color-change-by-clicking

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!