jQuery .on点击只运行一次

时间:2014-04-05 18:03:35

标签: javascript jquery

我正在为我的网站建立评级系统。 我对jQuery很新,并且不太明白为什么.on点击只运行一次。它应该每次我点击#ratenumbers2时运行。 另外,如果您对如何简化或编写此代码有任何其他建议,我会非常感激。

<!DOCTYPE html>
<html>
<head>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>

function fade_out() {$("#votersmessage").fadeOut(4000);}


$(document).ready(function () {
  $("#ratenumbers").on("click", "#ratenumbers2", function () {
    document.getElementById("votersmessage").innerHTML = "You can only rate once";
    setTimeout(fade_out, 2000);
  });
}); 
</script>
</head>
<body>
<?php 
$usersrating = 5; //I just added this for testing purposes
if(!$usersrating)
  {echo"
  <span id='ratetitle'>Your rating:</span><span id='ratenumbers'> 
  <span id='rate1' onmouseover='rate1()' onmouseout='rateblanc()'>&#9734;</span>
  <span id='rate2' onmouseover='rate2()' onmouseout='rateblanc()'>&#9734;</span>
  <span id='rate3' onmouseover='rate3()' onmouseout='rateblanc()'>&#9734;</span>
  <span id='rate4' onmouseover='rate4()' onmouseout='rateblanc()'>&#9734;</span>
  <span id='rate5' onmouseover='rate5()' onmouseout='rateblanc()'>&#9734;</span>
  <span id='rate6' onmouseover='rate6()' onmouseout='rateblanc()'>&#9734;</span>
  <span id='rate7' onmouseover='rate7()' onmouseout='rateblanc()'>&#9734;</span>
  <span id='rate8' onmouseover='rate8()' onmouseout='rateblanc()'>&#9734;</span>
  </span>";}
else
  {
  echo"
  <span id='ratetitle'>Your rating:</span><span id='ratenumbers'><span id='ratenumbers2'>";
  if($usersrating == 1){echo" &#9733; &#9734; &#9734; &#9734; &#9734; &#9734; &#9734; &#9734; ";}
  if($usersrating == 2){echo" &#9733; &#9733; &#9734; &#9734; &#9734; &#9734; &#9734; &#9734; ";}
  if($usersrating == 3){echo" &#9733; &#9733; &#9733; &#9734; &#9734; &#9734; &#9734; &#9734; ";}
  if($usersrating == 4){echo" &#9733; &#9733; &#9733; &#9733; &#9734; &#9734; &#9734; &#9734; ";}
  if($usersrating == 5){echo" &#9733; &#9733; &#9733; &#9733; &#9733; &#9734; &#9734; &#9734; ";}
  if($usersrating == 6){echo" &#9733; &#9733; &#9733; &#9733; &#9733; &#9733; &#9734; &#9734; ";}
  if($usersrating == 7){echo" &#9733; &#9733; &#9733; &#9733; &#9733; &#9733; &#9733; &#9734; ";}
  if($usersrating == 8){echo" &#9733; &#9733; &#9733; &#9733; &#9733; &#9733; &#9733; &#9733; ";}
  echo"</span></span>";
  }
?>
<span id='ratingend'></span>
<span id='votersmessage'></span>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

因为在fadeOut()之后您再次没有显示$("#votersmessage")。 也许像是

$("#ratenumbers").on("click", "#ratenumbers2", function () {
    $("#votersmessage").html("You can only rate once");
    $("#votersmessage").show(); //or fadeIn() for some class
    setTimeout(fade_out, 2000);
});

答案 1 :(得分:1)

因为在第一个fadeOut

之后永远不会显示该消息
$(document).ready(function () {
  $("#ratenumbers").on("click", "#ratenumbers2", function () {
    $("#votersmessage").fadeIn(500).html("You can only rate once");
    setTimeout(function(){$("#votersmessage").fadeOut(4000);}, 2000);
  });
});