javascript - 如何打乱不同部分标签的垂直顺序?

标签 javascript html jquery

我有一个很大的 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/

相关文章:

html - Bootstrap hero-unit 没有出现在网络上,可能是 z-index 错误

javascript - 即使在使用 tabs-right 之后,Bootstrap 选项卡仍显示在顶部

javascript - 从值数组中获取多个最大值

javascript - 浏览器在 Javascript 处理过程中不响应点击

javascript - 在 AngularJS 中动态更改类

javascript - JS - 强制打印死键

javascript - 你能说出为什么 javascript 函数没有在 profile.php 的提交按钮中执行吗

javascript - 在javascript中设置默认图像

javascript - jQuery slider 在第一次加载幻灯片时不显示效果

javascript - 谷歌脚本编辑器 : Apply to all sheets except 3 specific sheets