简体   繁体   English

未捕获的 ReferenceError:addToCart 未定义 javascript

[英]Uncaught ReferenceError: addToCart is not defined javascript

i am using javascript onclick function to make a function but it returns an error Uncaught ReferenceError: addToCart is not defined i don't know why here is my code我正在使用 javascript onclick 函数创建一个函数,但它返回一个错误 Uncaught ReferenceError: addToCart is not defined 我不知道为什么这是我的代码

my javascript code我的 JavaScript 代码

function addToCart(){
  var productname = $('pname').text();
  var productid = $('productid').text();
  var color = $('#color option:selected').text();
  var color = $('#size option:selected').text();
  var quantity = $('#qty').val();
  $.ajax({
    type: "POST",
    dataType: 'json',
    data:{
      color:color,
      size:size,
      quantity:quantity,
      productname:productname,
    },
    url: "cart/data/store"+productid,
    success:function(data)
    console.log(data);
  })

and my onclick input和我的点击输入

<input type="submit" class="btn btn-primary" onclick="addToCart()" value="add to cart">

你做了onclick="addToCart()"立即执行你应该onclick="addToCart"的功能。

This is probably happening because the browser isn't properly loading your function.这可能是因为浏览器没有正确加载您的函数。 I would try adding a console.log above and outside of your function definition to make sure it's being loaded.我会尝试在函数定义的上方和外部添加一个 console.log 以确保它正在加载。

More generally, if you're using jQuery, you probably want to attach that addToCart onclick handler in Javascript rather than in HTML.更一般地,如果您使用 jQuery,您可能希望在 Javascript 中而不是在 HTML 中附加addToCart onclick 处理程序。 See this question for more details: Add onclick event to button after document is ready with JS/JQuery selecting by class有关更多详细信息,请参阅此问题: 在文档准备好后,使用 JS/JQuery 按类选择将 onclick 事件添加到按钮

In the case of everything is okay then what you can do is insted of onclick in html在一切正常的情况下,你可以做的是在 html 中插入 onclick

<input type="submit" class="btn btn-primary" id="cart-btn" value="add to cart">

Script:脚本:

 $(document).ready(function(){
   function addToCart(){
   //function definition
 }
  $("#cart-btn").click(addToCart);
 });

I think your addToCart function is either not loading or not defined in the global scope!我认为您的addToCart函数未加载或未在全局范围内定义!

Example 1 (Function defined in global scope)示例 1(在全局范围内定义的函数)

 function hi() { alert("hi"); }
 <button onclick="hi()">Click Me</button>

Example 2 (onClick function not defined in global scope)示例 2(onClick 函数未在全局范围内定义)

 (() => { function hi() { alert("hi"); } })()
 <button onclick="hi()">Click Me</button>

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

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