简体   繁体   English

简单的jQuery元素html更改

[英]Simple jQuery element html change

I have this code: 我有以下代码:

$(document).ready(function() {
    $('#mobile-nav').click(function() {
        if($(this).html('<i class="fa fa-bars"></i>')){
            $(this).html('<i class="fa fa-times"></i>');
        } else {
            $(this).html('<i class="fa fa-bars"></i>');
        }

    });

});

When you first click on it, the html content changes as I expect, but when I click again the <i class="fa fa-bars"></i> are not set again. 当您第一次单击它时,html内容会按我的预期进行更改,但是当我再次单击时,不会再次设置<i class="fa fa-bars"></i>

What I'm doing wrong? 我做错了什么?

-----------------------------------------------UPDATE-------------------------------------- -----------------------------------------------更新- ------------------------------------

After reading these helpful answers and combining them into one the answer for this should be something like this: 阅读这些有用的答案并将它们组合为一个答案后,答案应该是这样的:

$(document).ready(function() {
    $('#mobile-nav').click(function() {
      if ($('i', this).hasClass("fa-bars")) {
          $('i', this).removeClass("fa-bars").addClass("fa-times");
      } else {
          $('i', this).removeClass("fa-times").addClass("fa-bars");
      }
    });    
});

Don't check it like that, check the class name. 不要那样检查,请检查类名。 Not to mention you're setting the HTML, not checking it. 更不用说您是在设置HTML,而不是对其进行检查。

if ($(this).hasClass("fa-bars")) {
    $(this).removeClass("fa-bars").addClass("fa-times");
} else {
    $(this).removeClass("fa-times").addClass("fa-bars");
}

This condition in the predicate: 谓词中的此条件:

$(this).html(...)

always returns $(this) , which is "truthy", so only the first part of the branch is ever taken. 总是返回$(this) ,这是“真实的”,因此只使用了分支的第一部分。

In any event (no pun intended) you should never test the serialised version of the HTML to maintain state. 在任何情况下(无双关语),您都不应测试HTML的序列化版本以保持状态。 You could check for a specific class ( .hasClass ) or use data attributes ( .data ) stored on the element, or a variable bound in the lexical scope, eg: 您可以检查特定的类( .hasClass )或使用存储在元素上的数据属性( .data ),或者使用在词法范围内绑定的变量,例如:

(function() {
    var state = false;
    $('#mobile-nav').on('click', function() {
       state = !state;
       if (state) {
           ...
       } else {
           ...
       }
    });
 })();

Just add the class if it is not present: 如果不存在,只需添加该类:

http://jsfiddle.net/x8dSP/2700/ http://jsfiddle.net/x8dSP/2700/

$(document).ready(function () {
    $('#mobile-nav li').click(function () {
        if ($(this).hasClass('fa-bars')) {
            $(this).removeClass('fa-bars');
            $(this).addClass('fa-times');
        } else {
            $(this).removeClass('fa-times');
            $(this).addClass('fa-bars');
        }
    });
});

相反的.click()事件使用.toggle()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM