简体   繁体   English

编写jquery add / remove类的更好方法

[英]Better way to write jquery add/remove class

I'm not an expert on JS and jQuery, but I would like to improve my knowledge. 我不是JS和jQuery的专家,但我想提高自己的知识。

I made this code that works for me, but I'm sure it can be done better. 我制作了适合我的代码,但我确信它可以做得更好。 can you help me and explain how to synthesize it? 你能帮我解释一下如何合成它吗? It's a piece of a slideshow when a URL is activated via a button, some images disappear and another appears. 当通过按钮激活URL时,这是一个幻灯片,一些图像消失,另一个图像出现。

<script>
  $(".green").click(function(e){
      window.location = "#img_green";
      $('#piz_green').css("display", "block");
      $('#piz_army').css("display", "none");
      $('#piz_red').css("display", "none");
      $('#piz_white').css("display", "none");
      $('#piz_blue').css("display", "none");
      $('#piz_black').css("display", "none");
  });
  $(".army").click(function(e){
      window.location = "#img_army";
      $('#piz_green').css("display", "none");
      $('#piz_army').css("display", "block");
      $('#piz_red').css("display", "none");
      $('#piz_white').css("display", "none");
      $('#piz_blue').css("display", "none");
      $('#piz_black').css("display", "none");
  });
  $(".red").click(function(e){
      window.location = "#img_red";
      $('#piz_green').css("display", "none");
      $('#piz_army').css("display", "none");
      $('#piz_red').css("display", "block");
      $('#piz_white').css("display", "none");
      $('#piz_blue').css("display", "none");
      $('#piz_black').css("display", "none");
  });
  $(".white").click(function(e){
      window.location = "#img_white";
      $('#piz_green').css("display", "none");
      $('#piz_army').css("display", "none");
      $('#piz_red').css("display", "none");
      $('#piz_white').css("display", "block");
      $('#piz_blue').css("display", "none");
      $('#piz_black').css("display", "none");
  });
  $(".blue").click(function(e){
      window.location = "#img_blue";
      $('#piz_green').css("display", "none");
      $('#piz_army').css("display", "none");
      $('#piz_red').css("display", "none");
      $('#piz_white').css("display", "none");
      $('#piz_blue').css("display", "block");
      $('#piz_black').css("display", "none");
  });
  $(".black").click(function(e){
      window.location = "#img_black";
      $('#piz_green').css("display", "none");
      $('#piz_army').css("display", "none");
      $('#piz_red').css("display", "none");
      $('#piz_white').css("display", "none");
      $('#piz_blue').css("display", "none");
      $('#piz_black').css("display", "block");
  });
</script>

Thank you. 谢谢。

To improve this code we also can improve html a little. 为了改进这个代码,我们也可以改进一下html。 We can add some class to identify elements and controls and after that - we might need only 6 lines of js 我们可以添加一些类来识别元素和控件,然后我们可能只需要6行js

Please try this 请试试这个

 $(".your-button-class").click(function(e) { const color = e.target.dataset.color; window.location = "#img_" + color; $('.your-div-class').css("display", "none"); $('div[data-color=' + color + ']').css("display", "block"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <button class="your-button-class" data-color="green">green</button> <button class="your-button-class" data-color="army">army</button> <button class="your-button-class" data-color="red">red</button> <button class="your-button-class" data-color="white">white</button> <button class="your-button-class" data-color="blue">blue</button> <button class="your-button-class" data-color="black">black</button> </div> <div class="your-div-class" data-color="green">green</div> <div class="your-div-class" data-color="army">army</div> <div class="your-div-class" data-color="red">red</div> <div class="your-div-class" data-color="white">white</div> <div class="your-div-class" data-color="blue">blue</div> <div class="your-div-class" data-color="black">black</div> 

There is no need for JavaScript here as you can do that with basic CSS as follows. 这里不需要JavaScript,因为您可以使用基本CSS执行此操作,如下所示。

Use proper links with anchors: 使用与锚点的正确链接:

<a href="#img_green">green</a>
<!-- repeat for other colors -->
<a href="#img_black">black</a>

Then use the :target pseudo-class as follows: 然后使用:target伪类 ,如下所示:

#piz_green,
#piz_army,
#piz_red,
#piz_white,
#piz_blue,
#piz_black {
  display: none;
}
#piz_green:target,
#piz_army:target,
#piz_red:target,
#piz_white:target,
#piz_blue:target,
#piz_black:target {
  display: block;
}

And by adding a parent element, you can simplify it as follows: 通过添加父元素,您可以按如下方式简化它:

#container > * {
  display: none;
}
#container > *:target {
  display: block;
}

When I highly suggest the use of common classes in this case, you could always use comma , separator in you selectors with show()/hide() to simplify your code (a little) like : 当我强烈建议在这种情况下使用公共类时,你总是可以在选择器中使用逗号,分隔符和show()/hide()来简化你的代码(一点点),如:

 $(".green").click(function(e) { window.location = "#img_green"; $('#piz_green').show(); $('#piz_army,#piz_red,#piz_white,#piz_blue,#piz_black').hide(); }); $(".army").click(function(e) { window.location = "#img_army"; $('#piz_army').show(); $('#piz_green,#piz_red,#piz_white,#piz_blue,#piz_black').hide(); }); $(".red").click(function(e) { window.location = "#img_red"; $('#piz_red').show(); $('#piz_green,#piz_army,#piz_white,#piz_blue,#piz_black').hide(); }); $(".white").click(function(e) { window.location = "#img_white"; $('#piz_white').show(); $('#piz_green,#piz_army,#piz_red,#piz_blue,#piz_black').hide(); }); $(".blue").click(function(e) { window.location = "#img_blue"; $('#piz_blue').show(); $('#piz_green,#piz_army,#piz_red,#piz_white,#piz_black').hide(); }); $(".black").click(function(e) { window.location = "#img_black"; $('#piz_black').show(); $('#piz_green,#piz_army,#piz_red,#piz_white,#piz_blue').hide(); }); 

Another suggestion with no need to change your HTML structure: 另一个建议,无需更改HTML结构:

 $(".green, .army, .red, .white, .blue, .black").click(function(e) { var color = $(this).prop('class'); window.location = "#img_" + color; $('[id^=piz_]').hide(); $('#piz_' + color).show(); }); 

Data attributes on the elements and a common class would make your life easier 元素和公共类的数据属性将使您的生活更轻松

 var slides = $(".slide"); // reference all the slides $("[data-action").on("click", function(e){ // bind the click var btn = $(this); // button that was clicked var color = btn.data("action"); // get the color slides.attr("hidden", true); // hide all the slides $("#piz_" + color).removeAttr("hidden"); // show the clicked color window.location.hash = "img_" + color; // update the hash }); 
 [hidden] { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button data-action="green">Green</button> <button data-action="red">Red</button> <button data-action="blue">Blue</button> <div class="slide_wrapper"> <div class="slide" id="piz_green">green</div> <div class="slide" id="piz_red">red</div> <div class="slide" id="piz_blue">blue</div> </div> 

function slideshow(image_id, block_id){
      window.location = image_id;
      $("[id^=piz_]").css("display", "none");
      $(block_id).css("display", "block");
  }

  $(".green").click(function(e){
      slideshow("#img_green", "#piz_green");
  });

Here is the solution I would go with. 这是我要采用的解决方案。 First I would add an arbitrary data attribute, in this case, colour. 首先,我将添加一个任意数据属性,在本例中为color。 Then I would add all my buttons with a corresponding data attribute. 然后我会添加所有带有相应数据属性的按钮。 Then attach to the click event of those buttons and call the following code. 然后附加到这些按钮的单击事件并调用以下代码。

 $('[data-action=toggle]').click(function(e){ $('div[data-color]:not([data-color=' + e.target.dataset.color + '])').hide(); $('div[data-color=' + e.target.dataset.color + ']').show(); }) 
 a{ margin-right: .5em; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div data-color="green">green</div> <div data-color="red">red</div> <div data-color="blue">blue</div> <div data-color="pink">pink</div> <div data-color="yellow">yellow</div> <a href="#" id="green" data-action="toggle" data-color="green">Green</a> <a href="#" id="green" data-action="toggle" data-color="red">Red</a> <a href="#" id="green" data-action="toggle" data-color="blue">Blue</a> <a href="#" id="green" data-action="toggle" data-color="pink">Pink</a> <a href="#" id="green" data-action="toggle" data-color="yellow">Yellow</a> 

You can consider attribute selector to hide all the element at once. 您可以考虑使用属性选择器一次隐藏所有元素。 Make sure to call hide() before show() 确保在show()之前调用hide() show()

 $(".green").click(function(e) { window.location = "#img_green"; $('[id^=piz]').hide(); $('#piz_green').show(); }); $(".army").click(function(e) { window.location = "#img_army"; $('[id^=piz]').hide(); $('#piz_army').show(); }); $(".red").click(function(e) { window.location = "#img_red"; $('[id^=piz]').hide(); $('#piz_red').show(); }); $(".white").click(function(e) { window.location = "#img_white"; $('[id^=piz]').hide(); $('#piz_white').show(); }); $(".blue").click(function(e) { window.location = "#img_blue"; $('[id^=piz]').hide(); $('#piz_blue').show(); }); $(".black").click(function(e) { window.location = "#img_black"; $('[id^=piz]').hide(); $('#piz_black').show(); }); 

You can store id of the image you want to show as custom data attribute with each button and then hide all images (by giving them a common class) with one line and show only the image you need by it's id from custom data attribute. 您可以使用每个按钮存储要显示为自定义数据属性的图像的ID,然后使用一行隐藏所有图像(通过为它们提供公共类),并仅显示自定义数据属性中的id所需的图像。

Example of button element: 按钮元素的示例:

<button data-slideshow-button="green">Green</button>

Example of slideshow element: 幻灯片元素的示例:

<div id="piz_green" class="slideshow-image"></div>

And then just run code like this as click handler: 然后只需运行像这样的代码作为点击处理程序:

$('[data-slideshow-button]').click(function(e){
  var showId = $(e.currentTarget).data('slideshowButton');
  window.location = '#img_' + showId;
  $('.slideshow-image').hide();
  $('#piz_' + showId).show();
});

As you did use piz_ for all classes in your HTML, you can easily use them in your JavaScript. 正如您对HTML中的所有类使用piz_ ,您可以在JavaScript中轻松使用它们。 For example, if you want to hide them all you can just type: $('[class^=piz_]').hide(); 例如,如果你想隐藏它们,你只需输入: $('[class^=piz_]').hide(); . This will hide all elements where the class starts with piz_ . 这将隐藏类以piz_开头的所有元素。

Now I made a quick example with this in action. 现在我做了一个快速的例子。 Please know I made just tile and a retry button to give you an example. 请知道我只是做了瓷砖和重试按钮给你举个例子。

 $("[class^=piz_]").click(function(){ // Make all div's with the class piz_* clickable $('[class^=piz_]').hide(); // Hide all elements var classAttr = '.'+$(this).attr("class"); // Get the class from the tile you clicked on $(classAttr).show(); // Show all tiles with the same class }); // This is just to get all tiles back and try it again. $('.retry').click(function() { $('[class^=piz_]').show(); }); 
 .piz_green { background:green; } .piz_blue { background:blue; } .piz_red { background:red; } .piz_orange { background:orange; } div, button { width:100px; height:100px; } .retry { display:block; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="piz_green"></div> <div class="piz_blue"></div> <div class="piz_red"></div> <div class="piz_orange"></div> <div class="piz_green"></div> <button class="retry"> Retry! </button> 

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

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