我是jQuery的初学者,想找点乐子。我正在尝试制作一个按钮,当点击时,它将改变页面的背景,以及改变按钮的文本。我只需要两个场景:-如果按钮显示为"1",则将按钮更改为"2",将背景更改为黑色;-如果按钮显示为"2“,则将按钮更改为"1”,将背景更改为白色;
我的代码适用于第一次单击,但您不能多次单击。
我做错什么了?耽误您时间,实在对不起。
http://jsfiddle.net/6fRbM/7/
这是我的HTML
<body>
<button id="lumiere">1</button>
</body>这是我的脚本
$(function() {
    $('#lumiere').bind('click', function(event) {
        if ($('#lumiere:contains("1")')) {
            $('body').css('background-color', "black")
            $('#lumiere').html('2')
        }
        else if ($('#lumiere:contains("2")')) {
            $('body').css('background-color', "white")
            $('#lumiere').html('1')
        }
    }
    );
}
);发布于 2013-06-28 23:22:32
稍微重构一下你的代码:
$(function() {
    $('#lumiere').click(function(event) {
        var $this = $(this);
        if ($this.text() === '1') {
            $('body').css('background-color', "black");
            $this.text('2');
        }
        else if ($this.text() === '2') {
            $('body').css('background-color', "white");
            $this.text('1');
        }
    });
});优化包括:
bind()是旧的,使用包含过滤器而不是click()快捷方式thison() text()。https://stackoverflow.com/questions/17368110
复制相似问题