使用for()循环搜索由JS制成的表

时间:2019-01-22 05:08:19

标签: javascript ajax for-loop html-table search-box

我正在尝试建立一个搜索栏,该搜索栏通过名称或电子邮件来循环通过API带来的数据而制成的表,但是我找不到我出了问题。控制台向我显示未捕获的ReferenceError:未在window.onload中定义sBar 请记住,我是JS的新手。真的很抱歉,这很愚蠢,但是我已经尽了最大的努力,但由于无法看到错误而感到非常沮丧

这是我的HTML

<body>
  <div>
    <label for="finder">Find User:</label>
    <input type="search" id="searchInput" name="sInput" placeholder="Search 
    user">
    <button id="sButton">Search</button>
  </div>
  <table class="table table-responsive">
    <thead class="thead-dark">
      <tr>
        <th scope="col">Id</th>
        <th scope="col">Name</th>
        <th scope="col">Username</th>
        <th scope="col">Email</th>
        <th scope="col">Address</th>
        <th scope="col">Phone</th>
        <th scope="col">Website</th>
        <th scope="col">Company</th>
      </tr>
    </thead>
    <tbody name="tTable">
    </tbody>
  </table>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js">
</script>
<script src="script.js">
</script>

Mi JS

window.onload = function(){    

    let uList = document.querySelector('[name =tTable]');  

    fetchCall('https://jsonplaceholder.typicode.com/users', getUsers);
    sButton.addEventListener('click', 
    fetchCall('https://jsonplaceholder.typicode.com/users', sBar), false);


  function sBar(getObject) {
    let sUser = getObject;
    let inputBar = document.getElementById("searchInput");
    let text = inputBar.textContent;
    let textView = text.toUpperCase();
    for (let i = 0; i < getObject.length; i++) {
         let uObject = sUser[i];
      if (textView == uObject.name || textView == uObject.email) {
        let new_tTable = document.createElement('tbody');
        uList.parentNode.replaceChild(new_tTable, uList)

        let row = uList.insertRow();   
        let idInput = document.createElement('td');
        let nameInput = document.createElement('td');     
        let usernameInput = document.createElement('td');    
        let emailInput = document.createElement('td');      
        let cityInput = document.createElement('td');      
        let phoneInput = document.createElement('td');      
        let websiteInput = document.createElement('td');      
        let companyInput = document.createElement('td');      

        idInput.textContent = uObject.id;
        nameInput.textContent = uObject.name;
        usernameInput.textContent = uObject.username;
        emailInput.textContent = uObject.email;
        cityInput.textContent = uObject.address.city;
        phoneInput.textContent = uObject.phone;
        websiteInput.textContent = uObject.website;
        companyInput.textContent = uObject.company.name;
        row.appendChild(idInput);
        row.appendChild(nameInput);
        row.appendChild(usernameInput);
        row.appendChild(emailInput);
        row.appendChild(cityInput);
        row.appendChild(phoneInput);
        row.appendChild(websiteInput);
        row.appendChild(companyInput);  
     } else {
       alert("User not found");         
     }
   }
} 


  function fetchCall(url, fn){
    fetch(url)
        .then(function(response){
            return response.json();
        })
        .then(function(endPoint){
            fn(endPoint);
        })
        .catch(function(error){
            console.error(error);
        })
    }

  function getUsers(getObject) {
    let user = getObject;      
      for (let i = 0; i < getObject.length; i++) {
        let userObject = user[i];
        let row = uList.insertRow();   
        let idInput = document.createElement('td');
        let nameInput = document.createElement('td');     
        let usernameInput = document.createElement('td');    
        let emailInput = document.createElement('td');      
        let cityInput = document.createElement('td');      
        let phoneInput = document.createElement('td');      
        let websiteInput = document.createElement('td');      
        let companyInput = document.createElement('td');      

        idInput.textContent = userObject.id;
        nameInput.textContent = userObject.name;
        usernameInput.textContent = userObject.username;
        emailInput.textContent = userObject.email;
        cityInput.textContent = userObject.address.city;
        phoneInput.textContent = userObject.phone;
        websiteInput.textContent = userObject.website;
        companyInput.textContent = userObject.company.name;
        row.appendChild(idInput);
        row.appendChild(nameInput);
         row.appendChild(usernameInput);
         row.appendChild(emailInput);
         row.appendChild(cityInput);
         row.appendChild(phoneInput);
         row.appendChild(websiteInput);
         row.appendChild(companyInput);        
        }
      } 
    }

4 个答案:

答案 0 :(得分:1)

设置事件时,您会调用该函数,但需要绑定它。

z

我还建议在全局范围内创建一个函数。

sButton.addEventListener('click', fetchCall.bind(this, 'https://jsonplaceholder.typicode.com/users', sBar), false);

答案 1 :(得分:0)

您可能要分别定义scan(file, multi.line=TRUE, what=list("",1L,"",""), sep="\n") 和其他函数。

window.onload

答案 2 :(得分:0)

您已将回调sBar()附加到搜索输入的onchange事件中。但是没有sBar()函数的定义(请注意,该函数不接受参数/参数)。您仅定义了一个具有相同名称“ sBar”的函数,该函数接受(需要)一个名为getObject的参数。

删除参数“ getObject”,并修改前几行以在搜索输入中获取当前输入的文本。获取搜索输入值的示例代码为:

var value = document.getElementById("searchInput").value;

旁注:

您可能需要使用其他事件发射器而不是onchange。仅当您将焦点放在输入元素而不是实际输入上时才会触发。

  

如果要跟踪键入的更改,请使用"onkeydown"。如果需要用鼠标捕获粘贴操作,请使用"onpaste"(IE,FF3)和"oninput"(FF,Opera,Chrome,Safari 1 )。

请通过this链接查看

答案 3 :(得分:0)

async/await & fetch()

核心功能基于async/awaitfetch(),请转到上面的链接以获取特殊语法。

老实说,我不知道如何用OP处理所有问题( O 原始 P ost )代码。通常,您应该分步骤考虑该过程:

  1. 从URL获取JSON。您确定fetchAll()有效吗?

  2. 使用fetchCall()获得JSON之后,将JSON传递给getUser()

  3. 如果fetchCall()返回一个值(似乎确实存在...),则将整个函数用作值。

  4. 事件侦听器和处理程序具有必须遵循的特定签名,并使用命名回调或匿名回调很重要:

命名回调(无参数*)

DOMObj.addEventListener('event', namedFunction);
function namedFunction(e) {...

命名回调(带参数)

DOMObj.addEventListener('event', function(e) {
  namedFunction(num, str);
});
function namedFunction(num, str) {...

匿名回调

DOMObj.addEventListener('event', function(e) {...

以下演示使用async function getUser(url, id)来简化Promises,使用fetch()并一次提取JSON一个用户ID。 function getData(与JSON一起返回) json getUser()

搜索输入已更改为type='number',因为用户的user.id属性对其进行了引用。它还封装在<form>标记中,因此回调function findUser(url, id)将由Submit事件触发。基本上,它是getUser()的函数包装器。


演示

<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet">
<style>
fieldset.fieldset {width:max-content;padding: 10px 0 0}
input.input, label.label {display:inline-block;font:inherit;width:9ch;height:30px;line-height:30px;vertical-align:middle;text-align:center;}
input.input {width:6ch;padding-right:0;margin-right:8px}
input.button {font:inherit;height: 30px;line-height:20px;}
</style>
</head>
<body>
  <main class='container'>
    <section class='row'>
      <form id='main' class='form inline-form'>
        <fieldset class='fieldset form-group'>
          <label class='label control-label float-left' for="find">User ID:</label>
          <input id="find" class='input form-control float-left' type="number" min='1' max='10'>
          <input class="button btn btn-dark btn-sm float-left" type='submit' value='Find'>
       </fieldset>
    </form>
  </section>
  <section class='row'>
  <table class="table table-responsive">
    <thead class="thead-dark">
      <tr>
        <th scope="col">ID</th>
        <th scope="col">Name</th>
        <th scope="col">Username</th>
        <th scope="col">Email</th>
        <th scope="col">Phone</th>
        <th scope="col">Company</th>
        <th scope="col">City</th>
        <th scope="col">Website</th>
      </tr>
    </thead>
  </table>
 </section>
</main>
<script>

const main = document.forms[0];

const getData = (user) => {
  const uList = document.querySelector('.table');
  let row = uList.insertRow();  
  let cell = idx => row.insertCell(idx);
  
  for (let i = 0; i < 8; i++) {
    let C = cell(i);
    switch(i) {
      case 0:
      user.id = user.id > 9 ? "" + user.id: "0" + user.id;
      C.textContent = user.id;
      break;
      case 1:
      C.textContent = user.name;
      break;
      case 2:
      C.textContent = user.username;
      break;
      case 3:
      C.textContent = user.email;
      break;
      case 4:
      C.textContent = user.phone;
      break;
      case 5:
      C.textContent = user.company.name;
      break;
      case 6:
      C.textContent = user.address.city;
      break;
      case 7:
      C.textContent = user.website;
      break;
      default:
      break;
    }
  } 
};

const getUser = async (url, id) => { 
  const response = await fetch(`${url}${id}`);
  const json = await response.json();
  return getData(json);
};

/*/ For debugging -- an IIFE variables are private. Parameters are required.
(async (u, i) => {
  const json = await getUser(u, i);
  console.log(json);
})(url, id);
/*/

const findUser = (e) => {
  e.preventDefault();
  const url = 'https://jsonplaceholder.typicode.com/users/';
  let id = Number(e.currentTarget.find.value);
  getUser(url, id);
};

main.addEventListener('submit', findUser);

</script>
</body>
</html>