简体   繁体   English

如何在我的代码中添加 if else 语句?

[英]How to add an if else statement in my code?

I am trying to an if/else statement added to this code where the toggle is already clicked to be able to click it again and change to another color我正在尝试将 if/else 语句添加到此代码中,其中已经单击了切换按钮,以便能够再次单击它并更改为另一种颜色

HTML HTML

<a class="reme" href="#"><i class="far fa-circle"></i> Remember Me</a>

JQUERY查询

$(".reme").click(function(){
$(this).css("color", "#1ABC9C");
$(this).find('i').toggleClass('far fa-cirle fas fa-circle');
});

You can add a style to your CSS and then just toggleClass for the button itself - as demonstrated below.您可以向 CSS 添加样式,然后为按钮本身添加toggleClass - 如下所示。

Let me know if you wanted something else.如果你想要别的东西,请告诉我。

I have also added an if version below, but would advise against using it.我还在下面添加了一个if版本,但建议不要使用它。


Demo演示

 // Click event $(".reme").click(function() { // Toggle class on the button $(this).toggleClass("green-text"); // Unchanged $(this).find('i').toggleClass('far fa-cirle fas fa-circle'); });
 .green-text { color: #1ABC9C; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class="reme">Toggle</button>


Alternative选择

You can use an if statement if you'd like, and check the inline .css value of color ... but this is definitely not the best way of doing this.如果愿意,您可以使用if语句,并检查color的内联.css值……但这绝对不是最好的方法。 Toggling classes will be much better for this particular use case.对于这个特定用例,切换类会更好。

 // Click event $(".reme").click(function() { // Check if the color is set inline to the rgb version of your color - as when changed this way it enters the hex as rgb if ( $(this).css("color") == "rgb(26, 188, 156)") { // Make it black if it is $(this).css("color", "black"); } else { // Set it as green if not $(this).css("color", "#1ABC9C"); } $(this).find('i').toggleClass('far fa-cirle fas fa-circle'); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class="reme">Toggle</button>

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

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