我想从HTML5中获取两项数据,并在点击功能和其中的功能中使用它们。
我遇到了问题,所以这是我目前的代码:
var test = [];
// This is a div class .quiz_list_row the ids are counted as #1 #2 #3...
$(".quiz_list_row").each(function(index){
// Gets the data necessary
// It comes from data-quizlist-id (HTML5)
$quiz_list_id = $(this).eq(index).data("quizlistId");
// It comes from data-quizlevel-reached (HTML5)
$quiz_level_reached = $(this).eq(index).data("quizlevelReached");
test[index] = $quiz_list_id;
// testing
alert("quiz_list_id: " +$quiz_list_id);
alert("level: "+$quiz_level_reached);
// click functions
$(this).click(function(){
// bla bla
// alert(test[index]) ???
});
});
答案 0 :(得分:1)
你在滥用.eq()
。试试这个(我删除了对.eq()
的调用):
var test = [];
// This is a div class .quiz_list_row the ids (inside it) are counted as #1 #2 #3...
$(".quiz_list_row").each(function(index){
// Gets the data necessary
// It comes from data-quizlist-id (HTML5)
$quiz_list_id = $(this).data("quizlistId");
// It comes from data-quizlevel-reached (HTML5)
$quiz_level_reached = $(this).data("quizlevelReached");
test[index] = $quiz_list_id;
// testing
alert("quiz_list_id: " +$quiz_list_id);
alert("level: "+$quiz_level_reached);
// click functions
$(this).click(function(){
// bla bla
// alert(test[index]) ???
});
});
你可能只想要这个:
$(".quiz_list_row").click(function(){
var $quiz_list_id = $(this).data("quizlistId");
var $quiz_level_reached = $(this).data("quizlevelReached");
alert("quiz_list_id: " +$quiz_list_id);
alert("level: "+$quiz_level_reached);
});
答案 1 :(得分:0)
在click事件周围使用闭包
// testing
alert("quiz_list_id: " + $quiz_list_id);
alert("level: " + $quiz_level_reached);
// click functions
(function(num) {
$(this).click(function() {
alert(test[num]) ? ? ?
});
})(index);
});