[英]jQuery selector for elements in wrapper
When I use $('.color-wrap div')
its select first div of both color-wrappers. 当我使用
$('.color-wrap div')
它选择了两个颜色包装器的第一个div。
I need to select only first but they must be as a group so I can't use 我只需要首先选择,但是它们必须作为一个组,所以我不能使用
$('.colorbox:first-child')
or $('.colorbox-hard:first-child')
. $('.colorbox:first-child')
或$('.colorbox-hard:first-child')
。
I want to jQuery treat them as a group of 6 divs - its because, I want to choose one random div from group of six. 我想用jQuery将它们视为6个div组-这是因为,我想从6个一组中选择一个随机div。
<div class="wrapper">
<div class="color-wrap">
<div class="colorbox"></div>
<div class="colorbox"></div>
<div class="colorbox"></div>
</div>
<div class="color-wrap">
<div class="colorbox-hard"></div>
<div class="colorbox-hard"></div>
<div class="colorbox-hard"></div>
</div>
</div>
How to select 1 div of div with class color-wrap only? 如何仅使用类色换选择div的1 div?
var divs = $('.color-wrap div'); for(var i = 0 ; i < divs.length; i++){ console.log(divs[i]); // You can use like this. }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="wrapper"> <div class="color-wrap"> <div class="colorbox"></div> <div class="colorbox"></div> <div class="colorbox"></div> </div> <div class="color-wrap"> <div class="colorbox-hard"></div> <div class="colorbox-hard"></div> <div class="colorbox-hard"></div> </div> </div>
var divs = $('.color-wrap .colorbox, .color-wrap .colorbox-hard');
var divs = $('.color-wrap .colorbox, .color-wrap .colorbox-hard');
If I understand you correctly you could do something like this. 如果我对您的理解正确,则可以执行以下操作。 refer to comments.
参考评论。
$(document).ready(function() { // Collect all divs for both wrappers in variable var group = $('.color-wrap').find('div'); // Store the amount of items in the group variable var groupCount = group.length; // Store random number between 0 and the amount of items minus 1 var randomIndex = Math.floor(Math.random() * groupCount); // Use the random number as the key for the group variable to store one of the divs var randomElement = group[randomIndex]; console.log(randomElement); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="wrapper"> <div class="color-wrap"> <div id="colorbox">One</div> <div id="colorbox">Two</div> <div id="colorbox">Three</div> </div> <div class="color-wrap"> <div id="colorbox-hard">Four</div> <div id="colorbox-hard">Five</div> <div id="colorbox-hard">Six</div> </div> </div>
$('.color-wrap:first-child div:first-child')
应该可以满足您的需求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.