我有一个小问答,询问什么时候是大萧条。有4个div包含十年,其中1920是正确的答案(第3个div)。在我的jQuery中,我把任何值为1920 ='correct_answer'的变量放在那里,当点击它时会有一条消息显示'正确'。任何其他答案都会提醒“错误”。为什么这不起作用?
<!doctype html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="hello.css">
</head>
<body>
<p class="question"> When was the Great Depression? </p>
<div class="answer" value="1940" id="answer_1"> 1940's </div>
<div class="answer" value="1980" id="answer_2"> 1980's </div>
<div class="answer" value="1960" id="answer_3"> 1960's </div>
<div class="answer" value="1920" id="answer_4"> 1920's </div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
grade();
})
function grade() {
var correct_answer = 1920;
if($('.answer').attr('value') == correct_answer) {
$(this).click(function() {
alert('Correct');
}) else {
alert('Wrong');
}
}
</script>
答案 0 :(得分:3)
稍微更改HTML以容纳data-attributes
<div class="answer" data-value="1940" id="answer_1"> 1940's </div>
<div class="answer" data-value="1980" id="answer_2"> 1980's </div>
<div class="answer" data-value="1960" id="answer_3"> 1960's </div>
<div class="answer" data-value="1920" id="answer_4"> 1920's </div>
将.click()事件绑定到您的元素。
$(function(){
var correctAnswer = "1920";
$(".answer").click(function(){
var $this = $(this);
var currentVal = $this.data("value");
if (currentVal === correctAnswer) {
//your logic goes here
}
});
});
答案 1 :(得分:0)
订单错误
$(document).ready(function() {
var correct_answer = 1920;
$(".answer").on("click", function() {
if ($(this).attr('value') == correct_answer) {
alert('correct');
} else {
alert('Wrong');
}
});
});
这是一个小提琴
答案 2 :(得分:0)
你可以这样做:
users.sort({a, b in a > b})
答案 3 :(得分:-1)
翻转IF语句:)
$(document).ready(function() {
grade();
})
function grade() {
var correct_answer = 1920;
$('.answer').click(function() {
if ($(this).attr('value') == correct_answer) {
alert('Correct');
} else {
alert('Wrong');
}
});
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!doctype html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="hello.css">
</head>
<body>
<p class="question">When was the Great Depression?</p>
<div class="answer" value="1940" id="answer_1">1940's</div>
<div class="answer" value="1980" id="answer_2">1980's</div>
<div class="answer" value="1960" id="answer_3">1960's</div>
<div class="answer" value="1920" id="answer_4">1920's</div>
</body>
</html>
&#13;