javascript - 使用 foreach 将 id/class 放入 HTML 中以获得确切值的正确方法?

标签 javascript jquery

我已经成功地显示了数据,这里是代码:

<?php 
  foreach($jawapan as $row_jawapan):
?>
  <li class="vote-li" >
    <div class="round-button-circle">
      <span></span>
      <h1><?php echo $row_jawapan->answer_text;?></h1>
      <input class="id_answer" type="hidden" value="<?php echo $row_jawapan->id_option;?>">
      <input class="answer_text" type="hidden" value="<?php echo $row_jawapan->answer_text;?>">
    </div>
  </li>
<?php endforeach; ?>

现在我想使用这段代码在用户点击它时获得准确的值:

$('.vote-li').on('click', function(){
  var id_question = $('.id_question').val(),
      answer_text = $('.answer_text').val(),
      user_id = $('.user_id').val(),
      id_option = $(this).prop('id');

  var data = {
    id_question: id_question,
    user_id: user_id,
    id_option: id_option,
    answer_text: answer_text
  };
  console.log(data);
});

现在每次用户点击 vote-li 类时,console.log 只显示第一个索引项,即使项值不同。我想我在 input 元素中写了 class/id 时犯了错误,但我不知道如何放置正确的 id/class 以便我的 jQuery 可以提取正确的数据。

最佳答案

代替 $('.id_question')$('.answer_text').val()$('.user_id') 使用 $(this).find('.id_question')$(this).find('.answer_text')$(this ).find('.user_id'),因此它将仅限于当前的 .vote-li

更正后的代码:

$('.vote-li').on('click', function(){
  var id_question = $(this).find('.id_question').val(),
      answer_text = $(this).find('.answer_text').val(),
      user_id = $(this).find('.user_id').val(),
      id_option = $(this).prop('id');

  var data = {
    id_question: id_question,
    user_id: user_id,
    id_option: id_option,
    answer_text: answer_text
  };

  console.log(data);
});

关于javascript - 使用 foreach 将 id/class 放入 HTML 中以获得确切值的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36282498/

相关文章:

javascript - 在 PHP 页面上用 Javascript 创建 XML 会导致 '<?' 被解释为 PHP

javascript - 使用 phonegap 和 google maps api 删除单个标记

javascript - jQuery 根据第一个输入的文本框值填充以数组命名的表单字段

javascript - 如何在重新加载页面时显示所有选中的复选框?

php - 注册后的时间计数

javascript - 使用 html5 和 javascript 在图像上制作网格

javascript - jQuery 用事件移除延迟闪烁效果

javascript - 尝试使用 CSS 和 Jquery 确定设备类型未按预期工作

javascript - 如何从输入字段中获取特定值

javascript - 如何将参数传递给函数,然后将其作为字符串传递给另一个函数?