jQuery星級評分實現過程詳解

螞蟻小編發表於2017-03-25

在實際應用中經常會看到星級評分程式碼的使用,下面就通過程式碼例項介紹一下次效果的實現過程,當然實現的方式有很多種,效果也不可能和實際應用中那樣絢麗,這裡只是介紹一下它的大體實現過程。

程式碼如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
ul{
  list-style:none;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript">
$(function(){
  $("#div li").bind({
    mouseout:function(){
      $(this).css("color","black").html("☆").prevAll().css("color", "black").html("☆")
    },
    mouseover:function(){
      $(this).css("color", "red").html("★").prevAll().css("color", "red").html("★");   
      $("#p").html(parseInt( $(this).index("#div li"))+1);
    }
  });
  $("#div li").mousedown(function(){
    $("#score").html(("你選擇的分數是" + (parseInt($(this).index("#div li")) + 1)));
    $(this).css("color", "red").html("★").prevAll().css("color", "red").html("★")
    $(this).unbind().prevAll().unbind().nextAll().unbind();
  });
})
</script>
</head>
<body>
<body>
<p id="p"></p>
<p id="score"></p>
<div id="div">
  <ul>
    <li>☆</li>
    <li>☆</li>
    <li>☆</li>
    <li>☆</li>
    <li>☆</li>
  </ul>
</div>
</body>
</body>
</html>

上面的程式碼實現了簡單的評分功能,下面介紹一下它的實現過程。

一.程式碼註釋:

1.$(function(){}),當文件結構完全載入完畢再去執行函式中的程式碼。

2.$("#div li").bind({}),為div下的li元素繫結事件處理函式,bind的引數是一個物件直接量,這樣就可以一次註冊多個。

3.mouseout:function(){

  $(this).css("color","black").html("☆").prevAll().css("color", "black").html("☆")

},註冊mouseout事件處理函式。

3.1.$(this).css("color","black"),將當前所在的li元素的顏色設定為黑色。

3.2.html("☆"),將當前li元素中的星星換成空心的。

3.3.prevAll(),獲取當前li元素前面所有的li元素。

3.4.css("color", "black").html("☆"),將顏色設定為黑色,並且將內容設定為空心星星,也就是沒有被選中。

4.mouseover:function(){

  $(this).css("color", "red").html("★").prevAll().css("color", "red").html("★")

},註冊mouseover事件處理函式。

4.1.$(this).css("color", "red"),將當前li的內容顏色設定為紅色。

4.2.html("★"),將li的內容設定為實心星星。

4.3.prevAll().css("color", "red").html("★"),將前面的所有li的顏色設定為紅色,並且內容為實心星星。

5.$("#p").html(parseInt( $(this).index("#div li"))+1),設定p元素中的內容,很簡單不用多說。

6.$("#div li").mousedown(function(){

  $("#score").html(("你選擇的分數是" + (parseInt($(this).index("#div li")) + 1)));

  $(this).css("color", "red").html("★").prevAll().css("color", "red").html("★")

  $(this).unbind().prevAll().unbind().nextAll().unbind();

}),為div下的li元素註冊mousedown事件處理函式。6.1.$("#score").html(("你選擇的分數是" + (parseInt($(this).index("#div li")) + 1))),將分數寫入指定的元素。

6.2.$(this).css("color", "red").html("★").prevAll().css("color", "red").html("★"),將當前li元素和它之前的li元素中的內容設定為實心星星,並且將顏色設定為紅色。

6.3.$(this).unbind().prevAll().unbind().nextAll().unbind(),解綁元素上註冊的事件處理函式。

二.相關閱讀:

1.prevAll()函式可以參閱jQuery prevAll()一章節。

2.index()函式可以參閱jQuery index()一章節。

3.nextAll()函式可以參閱jQuery nextAll()一章節。

相關文章