简体   繁体   English

如何手动测试JavaScript?

[英]How do I manually test JavaScript?

I'm trying to learn javascript by making a simple price checking website using the Best Buy products API. 我正在尝试通过使用Best Buy产品API创建一个简单的价格检查网站来学习JavaScript。

How do I "run" the javascript? 如何“运行” JavaScript? My form takes in a product ID number (the SKU) and sends it to validateSKU() on submit. 我的表单接受一个产品ID号(SKU),并在提交时将其发送给validateSKU()。 The function processData(data) searches for the product using the SKU. 函数processData(data)使用SKU搜索产品。

Nothing is happening when I test the site, and any help would be great; 当我测试该站点时,什么都没有发生,任何帮助都会很大。 thanks! 谢谢!

 <!DOCTYPE html> <html> <head> <title>Learn JavaScript</title> </head> <body> <form id="bestBuyForm" name="bestBuyForm" onsubmit="validateSKU()"> <input id="SKU" name="SKU" required="" type="text"> <label for="SKU">SKU</label> <input id="email" name="email" type="email"> <label for="email">Email</label> <input class="button" id="submit" name="submit" type="submit"> </form> <script> function validateSKU() { var SKU = document.forms["bestBuyForm"]["SKU"].value; var bby = require('bestbuy')('process.env.BBY_API_KEY'); var search = bby.products('sku=' + SKU); search.then(processData); } function processData(data) { if (!data.total) { console.log('No products found'); } else { var product = data.products[0]; console.log('Name:', product.name); console.log('Price:', product.salePrice); } } </script> </body> </html> 

Use web console to see what does happen and read about the console API . 使用Web控制台查看会发生什么,并阅读有关控制台API的信息

Try to bind validateSKU with HTML element addEventListener method. 尝试将validateSKU与HTML元素的addEventListener方法绑定。 Also you should prevent default form behaviour which cause page reloading on submit. 此外,您还应防止默认表单行为,该行为会导致在提交时重新加载页面。 Call event.preventDefault() . 调用event.preventDefault()

Working example code: 工作示例代码:

<html>
  <form id="someForm">
      ...
      <button type="submit">Submit</submit>
  </form>
  <script>
    function validateSKU(event) {
      console.log('IT works');
      event.preventDefault();
      // ...here your code
    }

    var form = document.getElementById('someForm');

    form.addEventListener('submit', validateSKU, false);
  </script>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM