编写此JQuery代码的更好方法

时间:2017-02-05 10:38:26

标签: javascript jquery

当页面加载/重新加载时我想要保留第一个带有背景颜色的按钮,当单击另一个按钮时,第一个按钮颜色会消失。

我为它制作了这段代码:



value = Lo

$(document).ready(function(){
  $(".target1").css("background-color", "red");
  $(".target1").css("color", "white");
  $(".target2").click(function(){
    $(".target1").css("background-color", "transparent");
    $(".target1").css("color", "black");
    $(".target2").css("background-color","red");
  });
});




我有很多其他按钮,所以在Jquery中做这种代码我觉得这不是最好的做法......我需要帮助向我解释一个更好的方法吗?我将感激你的教诲!

由于

3 个答案:

答案 0 :(得分:1)

您需要this功能:

$(document).ready(function() {
  $(".target").css("color", "black").css("background-color", "white");
  $(".target1").css("background-color", "red");
  $(".target1").css("color", "white");
  $(".target").click(function() {
    $(".target1").css("background-color", "none");
    $(".target").css("color", "black").css("background-color", "white");
    $(this).css("background-color", "red");
  });
});
<button class="target target1" type="button">
  Button 1
</button>
<button class="target target2" type="button">
  Button 2
</button>
<button class="target target3" type="button">
  Button 3
</button>
<button class="target target4" type="button">
  Button 4
</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

JSFiddle Example

希望这有帮助!

编辑:已移至代码段

答案 1 :(得分:1)

你可以这样缩小:

$(document).ready(function() {
  $(".btn").click(function() {
    $('.active').removeClass('active');
    $(this).addClass('active');
  });
});
.active {
  background-color: red;
  color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="collapse3">
  <ol>
    <button class="target1 btn" type="button" onclick="setURL('imgs/projects/FAB/F01-Fabrication/1.html')">F01-Fabrication-1</button>
    <br>

    <button class="target2 btn" type="button" onclick="setURL('imgs/projects/FAB/F01-Fabrication/2.html')">F01-Fabrication-2</button>
    <br>

    <button class="target3" type="button" onclick="setURL('imgs/projects/FAB/F01-Fabrication/3.html')">F01-Fabrication-3</button>
    <br>

    <a class="target4" type="button" onclick="setURL('imgs/projects/FAB/F01-Fabrication/4.html')">F01-Fbuttonbrication-4</button><br>
                        
<button class="target5" type="button" onclick="setURL('imgs/projects/FAB/F01-Fabrication/5.html')">F01-Fabrication-5</button><br>
 </ol>
</div>

答案 2 :(得分:0)

要设置多个属性,请尝试:

$("p").css({"background-color": "yellow", "font-size": "200%"}); 

在css()方法中传递一个对象。