简体   繁体   English

jQuery选择具有相同类名的所有元素

[英]jQuery select all elements with same class name

I'm implementing a rating system on my website and trying display a total score when the user mouses over any rating star. 我正在网站上实施评分系统,并试图在用户将鼠标悬停在任何评分星级上时显示总得分。 The problem is that the jQuery select is only selecting the first set of input elements. 问题在于jQuery select仅选择第一组输入元素。 So, in the html below, it's only selecting elements with id of "ax1" through "ax5". 因此,在下面的html中,它仅选择ID为“ ax1”至“ ax5”的元素。 What I'm trying to do is iterate through each "star" input element, check to see if the image is a filled star (there is javascript in the mouseover event of each element to flip the image from empty star to filled star), and if it's a filled star the score is increased. 我想做的是遍历每个“ star”输入元素,检查图像是否为实心的星星(每个元素的mouseover事件中都有javascript,将图像从空星星翻转为实心的星星),如果它是一颗实心的星星,则得分会增加。 Again, the problem is that only the first set of "stars" are being counted. 同样,问题在于只计算了第一组“星星”。

HTML: HTML:

            <div style="margin: 20px 0 0 0; float: left;">
            <div class="divStars" style="width: 130px; float: left;">
                <input type="image" name="ctl00$MainContent$ax1" id="MainContent_ax1" class="stars" onmouseover="<code to flip image>" src="style/EmptyStar.png" style="height:20px;width:20px;" />
                <input type="image" name="ctl00$MainContent$ax2" id="MainContent_ax2" class="stars" onmouseover="<code to flip image>" src="style/EmptyStar.png" style="height:20px;width:20px;" />
                <input type="image" name="ctl00$MainContent$ax3" id="MainContent_ax3" class="stars" onmouseover="<code to flip image>" src="style/EmptyStar.png" style="height:20px;width:20px;" />
                <input type="image" name="ctl00$MainContent$ax4" id="MainContent_ax4" class="stars" onmouseover="<code to flip image>" src="style/EmptyStar.png" style="height:20px;width:20px;" />
                <input type="image" name="ctl00$MainContent$ax5" id="MainContent_ax5" class="stars" onmouseover="<code to flip image>" src="style/EmptyStar.png" style="height:20px;width:20px;" />

            </div>
            <div style="margin-top: 3px; width: 600px; float: left;">
                <span>axs</span>
            </div>
        </div>
        <div style="margin: 20px 0 0 0; float: left;">
            <div class="divStars" style="width: 130px; float: left;">
                <input type="image" name="ctl00$MainContent$bx1" id="MainContent_bx1" class="stars" onmouseover="<code to flip image>" src="style/EmptyStar.png" style="height:20px;width:20px;" />
                <input type="image" name="ctl00$MainContent$bx2" id="MainContent_bx2" class="stars" onmouseover="<code to flip image>" src="style/EmptyStar.png" style="height:20px;width:20px;" />
                <input type="image" name="ctl00$MainContent$bx3" id="MainContent_bx3" class="stars" onmouseover="<code to flip image>" src="style/EmptyStar.png" style="height:20px;width:20px;" />
                <input type="image" name="ctl00$MainContent$bx4" id="MainContent_bx4" class="stars" onmouseover="<code to flip image>" src="style/EmptyStar.png" style="height:20px;width:20px;" />
                <input type="image" name="ctl00$MainContent$bx5" id="MainContent_bx5" class="stars" onmouseover="<code to flip image>" src="style/EmptyStar.png" style="height:20px;width:20px;" />
            </div>
            <div style="margin-top: 3px; width: 600px; float: left;">
                <span>bx blah blah</span>
            </div>
        </div>

Javascript: Javascript:

        $(document).on("mouseover", ".stars", function () {
        var score = 0;
        $("input[class='stars']").each(function (index, element) {
            // element == this
            if ($(element).attr("src") == "style/EmptyStar.png") {
                return false;
            }
            else {
                score = score + 1;
            };
        });
        debugger;
        $("#MainContent_lblScore").val(score);
    });

Returning false from the function inside the .each() call terminates the each loop. 从.each()调用内的函数返回false会终止每个循环。 The code as you have written it will terminate the first time it detects an empty star. 您编写的代码将在第一次检测到空星时终止。

Try doing a console.log($("input[class='stars']").length) to see how many you are getting. 尝试做一个console.log($("input[class='stars']").length)看看有多少。

I also agree that you should modify your selector. 我也同意您应该修改选择器。 "input.stars" is a generally a better selector than "input[class='stars']" because: 通常,“ input.stars”是一个比“ input [class ='stars']”更好的选择器,因为:

1) it will match <input class="stars anotherClass"> but your selector will not 1)它会匹配<input class="stars anotherClass">但您的选择器不会

2) browsers generally have faster selection of elements that are selected by class. 2)浏览器通常可以更快地选择按类选择的元素。 Technically you are selecting by class but you are using attribute syntax which probably doesn't trigger the optimized portion of the selection engine. 从技术上讲,您是按类别进行选择,但是您使用的是属性语法,这可能不会触发选择引擎的优化部分。

JSFiddle Example JSFiddle示例

Try this: 尝试这个:

$(document).on("mouseover", ".stars", function () {
    var score = 0;
    $("input.stars").each(function (index, element) {
        // element == this
        //if the star is not empty, add it to the score
        if ($(element).attr("src") != "style/EmptyStar.png") {
            score = score + 1;
        };
    });
    debugger;
    $("#MainContent_lblScore").val(score);
});

Mike Edwards is completely correct in pointing out that you stopped counting as soon as you hit an empty star. 迈克·爱德华兹(Mike Edwards)完全正确地指出,当您撞到一颗空星星时,您就停止了计数。 Actually it only returns out of that current function, and the each() will continue to execute. 实际上,它只会从当前函数中返回,并且each()将继续执行。 Ok, the each() will only discontinue execution if you return false , as seen in this example . 好的,仅当您返回falseeach()才会中止执行,如本示例所示 The function I have outlined counts all the non-empty stars, and uses a better selector. 我概述的功能会计算所有非空星星,并使用更好的选择器。

I notice that in the score aggregation you only grab the stars that are input elements, which makes sense; 我注意到,在分数汇总中,您仅抓住作为输入元素的星星,这很有意义; however, in the mouseover event, you apply it to any element that has the .stars class. 但是,在mouseover事件中,您可以将其应用于具有.stars类的任何元素。 Perhaps this is intentional so that they can mouse over a div that says "Show stars" or something, but if not you may wish to change that to 也许这是有意的,以便他们可以将鼠标悬停在显示“显示星星”之类的div上,但是如果没有,您可能希望将其更改为

$(document).on("mouseover", "input.stars", function () {

to avoid unexpected behavior. 避免意外行为。

Could you try with 你可以试试看吗

      $(".stars").each(function (index, element) {
        // element == this
        if ($(this).attr("src") == "style/EmptyStar.png") {
            return false;
        }
        else {
            score = score + 1;
        };
    });

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

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