我有这个标记:
<div data-answer=" True" class="question-container"></div>
用这个js:
Drupal.behaviors.articleQuiz = (function(){
var _attach = function(context){
$('.question-container', context)
.once()
.each(function(i, section){
new ArticleQuiz($(section));
});
};
return {
attach: _attach
};
})();
function ArticleQuiz($el){
this.$el = $el;
this.$el.data('answer'); // the value of this needs to be lower case
this.quizLogic();
return this;
}
ArticleQuiz.prototype.quizLogic = function(){
var THIS = this;
$('.quiz-cols a', this.$el)
.on('click',function(e) {
e.preventDefault();
var $target = $(e.target);
// exit if choice already made: users can't change their pick
if (THIS.$el.hasClass('answered')) return;
$target.addClass('selected');
THIS
.$el
//add correct or incorrect class depending on the selected answer and the correct answer
.addClass( ($target.data('value') == THIS.answer) ? 'correct':'incorrect' )
//add the answered class so in the future we know that this question was already answered
.addClass('answered');
});
return THIS;
};
最奇怪的是,在console.log
中,它以小写形式返回data-answer属性,但在html中它仍然如下所示:
我该怎么办?
注意: 该数据应答值由PHP动态填充。所以真正的标记看起来像这样
<div data-answer="<?php print render($content['field_paragraph_answer']); ?>" class="question-container"></div
答案 0 :(得分:0)
您没有在代码中设置实际HTML DOM元素的属性,查找下面的注释,我设置.data()
值,但您还必须使用attr()
手动设置属性为了更新HTML。
这部分并不总是必要的,因为jQuery会在后台跟踪data
。就好像以后需要CSS或jQuery选择器一样。
function ArticleQuiz($el){
this.$el = $el;
//get data('answer') and set to lowercase
this.answer = this.$el.data('answer').toLowerCase();
//set data and HTML attributes to lowercase value of this.answer
this.$el.data('answer', this.answer).attr('data-answer', this.answer);
this.quizLogic();
return this;
}