jQuery:如果类=活动?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3646631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:49:22  来源:igfitidea点击:

jQuery: if class=active?

jquery

提问by Karem

$(document).ready(function() {    
    $('a#fav').bind('click', function() {
        addFav(<?php echo $showUP["uID"]; ?>);
    });
});

I need to modify this so if the a#fav has class="active" then it should do

我需要修改这个,所以如果 a#fav 有 class="active" 那么它应该做

  removeFav(<?php echo $showUP["uID"]; ?>);

instead How can i do this?

相反,我该怎么做?

回答by Derek H

You want to use the hasClassfunction

您想使用该hasClass功能

$(document).ready(function() {    
    $('a#fav').bind('click', function() {
        if($(this).hasClass('active')) {
            removeFav(<?php echo $showUP["uID"]; ?>);
        }
        else {
            addFav(<?php echo $showUP["uID"]; ?>);
        }
    });
});

EDIT: And just for fun, another way to write it in a more condensed format

编辑:只是为了好玩,另一种以更简洁的格式编写它的方法

$(function() {    
    $('a#fav').bind('click', function() {
        var uID = <?php echo $showUP["uID"]; ?>;
        ($(this).hasClass('active') ? removeFav : addFav)(uID);
    });
});

回答by sluukkonen

$(document).ready(function() {    
    $('a#fav').bind('click', function() {
        if ($(this).hasClass('active'))
            removeFav(<?php echo $showUP["uID"]; ?>);
        else
             addFav(<?php echo $showUP["uID"]; ?>);
    });
});

回答by sod

$(function() {    
  $('a#fav').click(function() {
    return ($(this).hasClass('active'))
      ? removeFav('<?php echo $showUP["uID"]; ?>')
      : addFav('<?php echo $showUP["uID"]; ?>');
  });
});