簡體   English   中英

如何在jQuery中隨機化.hasClass()中的.class名稱

[英]How to randomize .class names inside .hasClass() in jQuery

我有一個代碼:

$(".user-items").each(function() {
  if ($(this).hasClass("don't know the code yet")) {
    $(this).fadeIn();
  } else {
    $(this).fadeOut();
  }
});

但我希望它像這樣工作:

$(".user-items").each(function() {
  if ($(this).hasClass(".people OR .photos OR .videos")) {
    $(this).fadeIn();
  } else {
    $(this).fadeOut();
  }
});

我想在每個.each()循環中隨機化3個類 ,並使所有匹配的元素成為fadeIn / fadeOut

注意* .hasClass的“OR”只是對我希望它如何工作的解釋

<a href="javascript:void(0);" class="user-items people">People</a>

<a href="javascript:void(0);" class="user-items photos">Photo</a>

<a href="javascript:void(0);" class="user-items videos">Videos</a>
...
...
...
lots of more .user-items classes with 3 given classes: .people, .photos, .videos

謝謝

您可以使用類數組然后使用random()方法獲取每次隨機類,如:

 var classes = ['photos', 'videos', 'people']; $(".user-items").each(function() { var random_class = classes[Math.floor((Math.random() * classes.length) + 0)]; console.log(random_class); if ($(this).hasClass(random_class)) { $(this).fadeIn(); } else { $(this).fadeOut(); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="javascript:void(0);" class="user-items people">People</a> <br> <a href="javascript:void(0);" class="user-items photos">Photo</a> <br> <a href="javascript:void(0);" class="user-items videos">Videos</a> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM