因此,我已经了解了如何使用event.PreventDefault()防止页面跳转并在jquery中返回false,但是由于某些原因,每当我单击链接时,页面仍会跳起来:\
每当用户单击时,我都在使用ClickSpark库显示动画,但我认为这不会导致页面跳转,但我可能是错的。我只是希望每次单击链接时页面都不会跳起来。
有趣的是,一旦完成导致页面跳转到顶部的初始单击,随后的单击就不会导致页面跳转。我不知道为什么会这样,请问对此有何评论。
这是我的代码:
<script>
$(document).ready(function() {
$("a.answer").on( "click", function( event ) {
event.preventDefault();
var current_answer = $(this);
var question_id = '<%= mcq.id %>';
var current_user = "<%= current_user.id %>";
if (current_answer.text() === $(".correct-choice").text()) {
clickSpark.setParticleImagePath('../../correct-answer-checkmark.png');
clickSpark.setParticleCount(50);
clickSpark.setParticleSize(20);
clickSpark.setParticleSpeed(12);
clickSpark.fireParticles($(this));
$(".slider").fadeIn("750");
current_answer.css({
backgroundColor: '#78e08f',
transition: ".25s all",
});
$("a.answer").not(this).each(function(){
$(this).css({
backgroundColor: '#fff',
transition: ".25s all"
});
});
}
else {
current_answer.css({
backgroundColor: '#e55039',
transition: ".25s all"
});
}
$.ajax({
url: "/verify_user_selected_answer",
type: "POST",
dataType: "json",
data: {user_id: current_user, question: question_id, answer: current_answer.text()},
success: function(response){
$("#display_result").text(response["result"]);
}
});
});
});
</script>
html
<% mcq.answers.each do |answer| %>
<div class="gr-question--choice">
<%= link_to answer, "javascript:void(0);", class: "answer" %>
</div>
<% end %>
rails实际的html输出:
<div class="gr-question--choice">
<a class="answer" href="javascript:void(0);">Yes</a>
</div>
<div class="gr-question--choice">
<a class="answer" href="javascript:void(0);">Maybe</a>
</div>
<div class="gr-question--choice">
<a class="answer" href="javascript:void(0);">No</a>
</div>
<div class="gr-question--choice">
<a class="answer" href="javascript:void(0);">Possibly</a>
</div>
<div class="gr-question--choice">
<a class="answer" href="javascript:void(0);">Perhaps</a>
</div>
console.log
jQuery.fn.init(5)
0: a.answer
1: a.answer
2: a.answer
3: a.answer
4: a.answer
context: document
length: 5
prevObject: jQuery.fn.init [document, context: document]
selector: "a.answer"
__proto__: Object(0)