我有一个很大的 html 文档,其中每个部分由 <section> </section>
分隔标签,例如:
<!DOCTYPE html>
<html>
<body>
<section>
<h1>A file</h1>
<form action="/action_page.php">
<p>Please select your gender:</p>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label><br>
<input type="radio" id="other" name="gender" value="other">
<label for="other">Other</label>
</section>
<br>
<section>
<p>Please select your age:</p>
<input type="radio" id="age1" name="age" value="30">
<label for="age1">0 - 30</label><br>
<input type="radio" id="age2" name="age" value="60">
<label for="age2">31 - 60</label><br>
<input type="radio" id="age3" name="age" value="100">
<label for="age3">61 - 100</label><br><br>
</section>
<input type="submit" value="Submit">
</form>
</body>
</html>
我怎样才能随机打乱部分的顺序?也就是说,我想每次用户加载页面时随机切换该部分的顺序?
最佳答案
要随机排序,您可以使用 sort()
方法连同 Math.random()
重新排序元素。另请注意,您的 HTML 需要稍微更改以使逻辑更简单 - 主要是通过添加新的 div
section
周围包含它们的元素,并确保 <form>
元素包装所有 section
内容。试试这个:
let $container = $('.sections');
$container.find('section').sort((a, b) => Math.random() > 0.5 ? 1 : -1).prependTo($container);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="/action_page.php">
<h1>A file</h1>
<div class="sections">
<section>
<p>Please select your gender:</p>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label><br>
<input type="radio" id="other" name="gender" value="other">
<label for="other">Other</label>
</section>
<section>
<p>Please select your age:</p>
<input type="radio" id="age1" name="age" value="30">
<label for="age1">0 - 30</label><br>
<input type="radio" id="age2" name="age" value="60">
<label for="age2">31 - 60</label><br>
<input type="radio" id="age3" name="age" value="100">
<label for="age3">61 - 100</label><br><br>
</section>
</div>
<input type="submit" value="Submit">
</form>
关于javascript - 如何打乱不同部分标签的垂直顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66476425/