首页 > 解决方案 > 使用 html onclick 提交按钮,搜索 js 数组,然后在原始 html div 中显示特定数据

问题描述

正在观看 youtube 视频,试图学习如何在数组中搜索特定的条目数据?

下面是一个使用 console.log 的 js 数组示例

js数组示例:

    var data = {
  username: "john",
  email: "28@GSDF.COM",
  status: true,
  id: 25
};

var data = {
  username: "jIM",
  email: "27@GSDF.COM",
  status: false,
  id: 23
};

var data = {
  username: "Jane",
  email: "25@GSDF.COM",
  status: false,
  id: 22
};

{
  console.log(data);
}

下面是html,我想让它显示来自上面js数组的特定结果,带有onclick提交按钮来搜索数组?然后在 html div 中显示/打印回来。

<html>
<head>
<title>get value</title>


    <script type="text/javascript">
    function getDisplay(){
    var username = document.getElementById("username").value;
    var email = document.getElementById("email").value;
    document.getElementById("display").innerHTML = "username" +  username + "<br/>email" + email;
    }
</script>

</head>
<body>

  <div id="whole">
        Username : <input type="text" name="username" id="username">

        Email : <input type="email" name="email" id="email"></br>


        <button onclick=getDisplay()>Submit</button>

  </div>
  <div id="display">
  </div>


</body>
</html>

如果您能推荐任何视频或阅读内容以帮助我学习,将不胜感激。

标签: javascriptarrayssearch

解决方案


对象数组应如下所示:

      var arr = [{
                  username: "john",
                  email: "28@GSDF.COM",
                  status: true,
                  id: 25
                 },
                {
                  username: "jIM",
                  email: "27@GSDF.COM",
                  status: false,
                  id: 23
                },
                {
                  username: "Jane",
                  email: "25@GSDF.COM",
                  status: false,
                  id: 22
                }
               ]

在您的代码中,您想要执行以下操作:

    <html>
     <head>
        <title>get value</title>


    <script type="text/javascript">

    var arr = [/*Your data here */];

    function getDisplay(){
           var username = document.getElementById("username").value;
           var email = document.getElementById("email").value;

           document.getElementById("display").innerHTML = "username" +  username + "<br/>email" + email;

      for(let i = 0; i < arr.length; i++) {
          let element = arr[i];
          //Your search logic goes here
      }
    }
</script>

</head>
  <body>

      <div id="whole">
              Username : <input type="text" name="username" id="username">

        Email : <input type="email" name="email" id="email"></br>


        <button onclick=getDisplay()>Submit</button>

  </div>
  <div id="display">
  </div>


</body>
</html>

推荐阅读