简体   繁体   English

星级评分系统jquery

[英]Star rating system jquery

I'm trying to make a star rating system, where if you click the star it will show the rating. 我正在尝试建立星级评分系统,如果您单击星级,它将显示评分。

(fyi i have multiple of these divs so that is why i have not given each star(span) a unique ID) (仅供参考,我有多个这样的div,所以这就是为什么我没有给每个星星(跨度)分配唯一的ID)

Html: HTML:

    <div id="rating1" class="rating">
        <span>★</span><span>★</span><span>★</span><span>★</span><span>★</span>
    </div>

jQuery: jQuery的:

    $(document).ready(function(){

$("#rating1 span:nth-child(1)").click(function()
{
    if (x == 5)
    {
        alert("You rate 1 star");
    }
    if (x == 4)
    {
        alert("You rate 2 star");
    }
    if (x == 3)
    {
        alert("You rate 3 star");
    }
    if (x == 2)
    {
        alert("You rate 4 star");
    }
    if (x == 1)
    {
        alert("You rate 5 star");
    }
  });
});

If you are wondering why the numbers are flipped it's because of the css where I made it so that the preceeding stars would light up when you hover over a star, since you can only make the succeeding one light up i had to reverse them using direction:rtl; 如果您想知道数字为什么会被翻转,那是因为css是我制作的,因此当您将鼠标悬停在恒星上方时,前面的恒星会亮起,因为您只能使后续的恒星亮起,因此我不得不使用方向将其反转:rtl;

Here's the problem, instead of the 1 inside of $("#rating1 span:nth-child(1)") i want to have the variable X and I want X to depend on which one i clicked, if i click the first star x=5 etc. I am new to jQuery and would really appreciate an answer that i could understand. 这是问题所在,而不是$(“#rating1 span:nth-​​child(1)”)中的1,我想要变量X,并且如果我单击第一个星号,我希望X取决于单击的是哪个x = 5等。我是jQuery的新手,非常感谢我能理解的答案。 The "alert" is just a test, I actually want it to show the rating underneath. “警报”只是一个测试,我实际上希望它显示下面的等级。

If anything is unclear, ask and i will update my question, forgive me if it is confusing, I am a beginner, both to programming, and stackoverflow. 如果尚不清楚,请询问,我将更新我的问题,如果它令人困惑,请原谅我,我是编程和stackoverflow的初学者。

Change 更改

$("#rating1 span:nth-child(1)")

to

$("#rating1 span")

and use .index to get the index of the clicked element: 并使用.index获取clicked元素的索引:

 $("#rating1 span").click(function() { var x = $(this).index() + 1; alert(x); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="rating1"> <span>1</span><span>2</span><span>3</span><span>4</span><span>5</span> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM