【问题标题】:How would I make this only display one result and add a randomize button?我如何让它只显示一个结果并添加一个随机按钮?
【发布时间】:2017-01-12 04:25:18
【问题描述】:

所以我有这段代码,它使用 Jput 在 JSON 文件中显示适合变量的所有对象。

<script>
$(document).ready(function(){

$("#tbody").jPut({
    ajax_url:"valid_data.json",
    prepend:true, 
    name:"tbody_template",
});

});
</script>  

<table jput="t_template">
 <tbody jput="tbody_template">
     <tr>
         <td>{{First Name}}</td>
         <td>{{Middle Name}}</td>
         <td>{{Last Name}}</td>
         <td>{{Nationality}}</td>
         <td>{{Birthplace}}</td>
         <td>{{Age}}</td>
     </tr>
 </tbody>
</table>

<table>
 <tbody id="tbody">
 </tbody>
</table>

<script src="jquery-1.12.3.min.js"></script>
<script src="jput.min.js"></script>

代码工作正常,(可以在http://fooda.website/test2.html 看到实际操作)但我需要一个按钮,当单击该按钮时会选择一个随机数组并仅显示该数组结果。

Javascript 知识很少,所以不知道如何去做。在我被建议转换为 JSON 之前,有一些以前的代码链接到 CSV 文件,但我不知道如何在其中实现它。

【问题讨论】:

    标签: javascript html json


    【解决方案1】:

    不确定.jPut() 的选项,但一种选择是将所有tr 元素style 设置为display:none,然后从table 中选择随机tr 并将tr 设置为@ 987654330@.

    根据链接文档,done 选项在JSON 返回时被调用。

    <!DOCTYPE html>
    <html>
    
    <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
      <script src="http://fooda.website/jput.min.js"></script>
    </head>
    
    <body>
      <script>
        $(document).ready(function() {
          var tr, button = $("button");
          $("#tbody").jPut({
            ajax_url: "http://fooda.website/valid_data.json",
            prepend: true,
            name: "tbody_template",
            done: function(e) {
              tr = $("table #tbody tr").hide();
              button.removeAttr("disabled")
            }
          });
    
          button.click(function() {
            tr.hide();
            var rand = Math.floor(Math.random() * tr.length);
            tr.eq(rand).show()
          });
        });
      </script>
      <button disabled>click</button>
      <table jput="t_template" style="display: none;">
        <tbody jput="tbody_template" style="display: none;">
          <tr>
            <td>{{First Name}}</td>
            <td>{{Middle Name}}</td>
            <td>{{Last Name}}</td>
            <td>{{Nationality}}</td>
            <td>{{Birthplace}}</td>
            <td>{{Age}}</td>
          </tr>
        </tbody>
      </table>
      <table>
        <tbody id="tbody">
        </tbody>
      </table>
    </body>
    
    </html>

    plnkrhttp://plnkr.co/edit/NURw4djMh9Jp23v3bINP?p=preview

    【讨论】:

    • 感谢@guest271314 的回复,但是这不起作用...单击按钮时,没有显示任何内容。可能会干扰jput?如果有帮助,可以在此处找到一些文档:github.com/shabeer-ali-m/jPut
    猜你喜欢
    • 1970-01-01
    • 2021-04-25
    • 2021-03-27
    • 1970-01-01
    • 2010-12-13
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多