不在JQuery中记录.data(事件)

问题描述 投票:0回答:1

我在JQuery中记录.data事件时遇到问题。这是我的代码:

我正在使用这个对象数组附加到DOM。

    var questions= [
  {
    question: 'Areosmith and Run DMC wanted you to do what?',
    choices:  ['Walk this way','Live on a prayer','Dream on'],
    answer:   'Dream on',
    gif:      'assets/images/aerosmith.gif',
  },
  {
    question: 'In 1975 Van McCoy ask you to do what?',
    choices:  ['Stay Alive','Move Side to Side','The Hustle'],
    answer:   'The Hustle',
    gif:      'assets/images/hustle.gif',
  }
]

下面是我为每个对象的每个选项创建一个函数的地方。当问题被调用时,我正在为数组中的每个选项创建一个“DIV”,并将它们附加到一个名为问题的ID中。

function newQuestion(){

  for(var i=0; i<questions[currentQuestion].choices.length; i++){
  var answerList = $('<div>');
  answerList.text(questions[currentQuestion].choices[i]);
  answerList.addClass('chooseAnswer');
  answerList.attr("data-choiceValue",questions[currentQuestion].choices[i]);
  $('#question').append(answerList);
}

$('.chooseAnswer').on('click', function() {
  pickedAnswer = ($(this).data("data-choiceValue"));
  console.log(pickedAnswer);
});
}

当我尝试记录pickAnswer我得到一个未定义。你能帮帮我吗如果需要,我可以提供更多信息。

jquery dom
1个回答
0
投票

你可以使用data.attr("data-choiceValue")获得.data("choiceValue")属性

如果你用data设置attr('data-choiceValue' , 'something')你可以使用attr('data-choiceValue')得到它

如果你用data设置data('choiceValue' , 'something')你可以使用data('choiceValue')得到它

var questions= [
  {
    question: 'Areosmith and Run DMC wanted you to do what?',
    choices:  ['Walk this way','Live on a prayer','Dream on'],
    answer:   'Dream on',
    gif:      'assets/images/aerosmith.gif',
  },
  {
    question: 'In 1975 Van McCoy ask you to do what?',
    choices:  ['Stay Alive','Move Side to Side','The Hustle'],
    answer:   'The Hustle',
    gif:      'assets/images/hustle.gif',
  }
];
var currentQuestion = 0;
newQuestion();

function newQuestion(){

  for(var i=0; i<questions[currentQuestion].choices.length; i++){
  var answerList = $('<div>');
  answerList.text(questions[currentQuestion].choices[i]);
  answerList.addClass('chooseAnswer');
  answerList.attr("data-choiceValue",questions[currentQuestion].choices[i]);
  $('#question').append(answerList);
}

$('.chooseAnswer').on('click', function() {
  pickedAnswer = ($(this).attr("data-choiceValue"));
  console.log(pickedAnswer);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="question"></div>
© www.soinside.com 2019 - 2024. All rights reserved.