javascript - 为我认为我定义的数组获取 Uncaught ReferenceError

标签 javascript jquery html ajax

错误“Uncaught ReferenceError: answers is not defined”问题是我以为我定义了变量。

我的代码摘要。

我有一个类,在单击时打开,然后另一个函数映射这些答案并将其放入数组答案中。

我然后使用 ajax 将输入到表单中的名称和我刚刚制作的数组发送到 php 文档。数组是给我带来麻烦的部分

live version on the site

Jsfiddle

$(document).ready(function() {


  //catch this values, because you will use these for more than one time
  var answers = [];



  function getAnswers() {
      answers = []; //empty old answers so you can update it
      $.map($('.on'), function(item) {
        answers.push($(item).data('value'));
      });
    }
    //init the answers in case you use it before click
  getAnswers();


  $(document).on('click', 'img', function(e) {
    e.preventDefault();
    $(this).toggleClass('on');

    //trigger the state change when you click on an image
    $(document).trigger('state-change');
  });

  //get answers when event was triggered
  $(document).on('state-change', function(e) {
    getAnswers();
  });

  $('#btn-show').click(function() {
    alert(answers.join(',') || 'nothing was selected');
  });



});
//ajax to send the data to php file
$(document).on('click', '#btn-show', function() {
  $.ajax({
    type: "POST",
    url: ".../inc/insert.php", //"/path/to/script.php"
    data: {
      "name": $('input[name="name"]').val(),
      "choices": answers
        //this is the part giving me an error
    },
    success: function(response) {
      alert(response);
      //the response variable contains whatever your PHP echoes out --
    }

  });

});
/* style for the selectable images  */

.choices {
  margin: 8px;
  font-size: 16px;
  height: 100px;
  width: 100px;
}
/* this shows the user which item has been selecting along with making a searchable class for the program */

.on {
  padding: 10px;
  background-color: red;
}
<head>
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script type="text/javascript" src="js/javascript.js"></script>
  <LINK REL=StyleSheet HREF="css/code.css" TYPE="text/css">

  <!DOCTYPE HTML>

  <head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script type="text/javascript" src="js/javascript.js"></script>
    <LINK REL=StyleSheet HREF="css/code.css" TYPE="text/css">
  </head>

  <body>
    <form method="post">
      Name
      <input type="text" name="name" />
      <br>
      <img src="img/m_bacon.jpg" alt="Bacon" class="choices" data-value="0">
      <br>
      <img src="img/m_beef.jpg" alt="Beef" class="choices" data-value="1">
      <br>

      <button id="btn-show">Submit</button>
  </body>

  </html>

最佳答案

您遇到范围问题。请注意,您在 $(document).ready(function () {...} 函数中声明了 var answers = [],但是您的点击事件在 ready 函数。

这里还有你的 fiddle 的编辑版本:http://jsfiddle.net/ku9pwo4c/1/ (请注意,由于 AJAX 请求 url,它不适用于 JS Fiddle,但如果您粘贴它,假设您的 PHP 端点正常工作,它应该可以工作。)

这是一个简化的例子:

$(document).ready(function () {
    var answers = [];
});

$(document).on('click', '#btn-show', function () {
    // This will be undefined because answers was declared in a 
    // different function scope.
    console.log(answers);
});

一个可能的解决方法是将您的点击事件处理程序移到就绪函数中:

$(document).ready(function () {
    var answers = [];
    $(document).on('click', '#btn-show', function () {
        // This time answers will be `[]`
        console.log(answers);
    });
});

我还添加了一个工作示例的片段:

$(document).ready(function () {
  var answers = [1, 2, 3, 4];
  $(document).on('click', '#btn-show', function () {
    console.log(answers);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="btn-show">Click me!</button>

关于javascript - 为我认为我定义的数组获取 Uncaught ReferenceError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26455509/

相关文章:

javascript - 如何使用 jQuery 的 droppble 函数添加自定义 DIV?

javascript - Rails 应用程序中的无限滚动

javascript - 更高级的 javascript 模式的困难

html - 可变高度标题下方的可滚动 div

javascript - JQuery 节点检查是否不为空

javascript - Accordion 中的内容从左侧滑入

javascript - 错误 : No Firebase App '[DEFAULT]' has been created - call Firebase App. 初始化应用程序()

javascript - 如何在 MAC 上的 Chrome 开发者工具中取消隐藏过滤消息

javascript - 在 JavaScript 中使用另一个字典创建字典时出现意外标记

jquery - 将变量传递给 tr :contains using jquery