通过 jQuery 更改文本来制作 div 切换单词?

Make a div toggle words by changing the text via jQuery?

当我点击按钮时,添加了一个 class,文本从 "Get in touch" 变为 "Work." 但是,当我再次点击按钮时 [=33] =] 文本没有变回 "Get in touch." 为什么它不起作用?

小提琴:http://jsfiddle.net/cLgkwjhb/

HTML

<a id="contact-button" href="#">Get in touch</a>

CSS

#contact-button {
    background: #000;
    background-size: 24px;
    color: #fff;
    text-decoration: none;
    text-transform: uppercase;
    font-weight: bold;
    padding: 10px 20px;
}

JS

jQuery('#contact-button').click(function( e ){

    e.preventDefault();
    jQuery(this).addClass('work-button').text('Work');

});

jQuery('#contact-button.work-button').click(function( e ){

    e.preventDefault();
    jQuery(this).removeClass('work-button').text('Get in touch');

});

它不起作用仅仅是因为当您设置该点击处理程序时 #contact-button.work-button 不存在。由于您稍后添加了 class,因此在该行代码运行时,jQuery 无法将任何元素与该选择器匹配。

您可以做的是在一个单击处理程序中使用所有逻辑

jQuery('#contact-button').click(function (e) {
    e.preventDefault();
    jQuery(this).toggleClass('work-button').text(function (i, text) {
        return text === 'Work' ? 'Get in touch' : 'Work';
    });
});

jQuery('#contact-button').click(function (e) {
    e.preventDefault();
    jQuery(this).toggleClass('work-button').text(function (i, text) {
        return text === 'Work' ? 'Get in touch' : 'Work';
    });
});
#contact-button {
    background: #000;
    background-size: 24px;
    color: #fff;
    text-decoration: none;
    text-transform: uppercase;
    font-weight: bold;
    padding: 10px 20px;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a id="contact-button" href="#">Get in touch</a>

或者使用像 .on() 这样的动态选择器,但这并不优雅 :)

您可以跟踪点击次数而不是添加 class,如果点击次数可以被 2((c++ % 2 == 0)) 整除,请将文本更改为 Work否则 Get in touch.

var c = 0;
jQuery('#contact-button').click(function(e) {
  e.preventDefault();
  jQuery(this).text((c++ % 2 == 0) ? 'Work' : 'Get in touch');
});
#contact-button {
  background: #000;
  background-size: 24px;
  color: #fff;
  text-decoration: none;
  text-transform: uppercase;
  font-weight: bold;
  padding: 10px 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a id="contact-button" href="#">Get in touch</a>

你可以这样做:

fiddle

    var work = false;
    jQuery('#contact-button').click(function( e ){

        e.preventDefault();
        work = !work;
        jQuery(this).toggleClass('work-button').text(work ? 'Work' : 'Get in touch');


    });

基本上使用一个事件监听器,因为在你原来的情况下,两个函数都被调用了。

试试这个:- http://jsfiddle.net/cLgkwjhb/5/

jQuery('#contact-button').click(function( e ){

    e.preventDefault();
    jQuery(this).toggleClass('work-button');

    if ($(this).text() == "Work")
       $(this).text("Get in touch")
    else
       $(this).text("Work");

});