Javascript 将单选按钮转换为星级

Javascript 将单选按钮转换为星级,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我正在尝试将表单中的单选按钮转换为星级 我使用的是nintex表单,单选按钮的DOM结构如下所示 <table class="controls rating"> <tr> <td> <span> <input type="radio" name="review-rating" id="1" value="1" /> <label for="1">1</label>

我正在尝试将表单中的单选按钮转换为星级

我使用的是nintex表单,单选按钮的DOM结构如下所示

<table class="controls rating">
<tr>
<td>
    <span>
        <input type="radio" name="review-rating" id="1" value="1" />
        <label for="1">1</label>
    </span>
</td>
<td>
    <span>
        <input type="radio" name="review-rating" value="2" id="2" />
        <label for="2">2</label>
    </span>
</td>
<td>
    <span>
        <input type="radio" name="review-rating" value="3" id="3" />
        <label for="3">3</label>
    </span>
</td>
<td>
    <span>
        <input type="radio" name="review-rating" value="4" id="4" />
        <label for="4">4</label>
    </span>
</td>
<td>
    <span>
        <input type="radio" name="review-rating" value="5" id="5" />
        <label for="5">5</label>
    </span>

</td>
</tr>
</table>

1.
2.
3.
4.
5.
现在我发现了一个JSFIDLE,它实现了我所期望的功能,但是dom结构不同

我做了一些调整,使单选按钮显示为星形,但它没有按预期工作

我希望顶部的星级与底部的星级相同。

附言:如果底部的那个在修改后不起作用,也可以。我只希望明星评级对我的DOM结构起作用(fiddle中排名第一)

问题是:你的“标签”彼此不相邻。将css和事件选择转换为您的“td”


试试这个,我刚刚添加了撤销

$('.controls.rating')
    .addClass('starRating') //in case js is turned off, it fals back to standard radio button
    .on('mouseenter', 'label', function(){
            DisplayRating($(this)); // when we hover into a label, show the ratings
        }
    )
    .on('mouseleave', function() {
        // when we leave the rating div, figure out which one is selected and show the correct rating level
        var $this = $(this),
            $selectedRating = $this.find('input:checked');
        if ($selectedRating.length == 1) {
            DisplayRating($selectedRating); // a rating has been selected, show the stars
        } else {
            $this.find('label').removeClass('on'); // nothing clicked, remove the stars
        };
    }
);

var DisplayRating = function($el){
    // for the passed in element, add the 'on' class to this and all prev labels
    // and remove the 'on' class from all next labels. This stops the flicker of removing then adding back
    $el.addClass('on');
    $el.parent('label').addClass('on');
    $el.closest('td').prevAll().find('label').addClass('on');
    $el.closest('td').nextAll().find('label').removeClass('on');
};
编辑:我最近注意到一个bug,所以我编辑了它并修复了这个bug


您需要使用
find
删除较深节点上的
子节点
仅在一级子节点上有效


把星星放在桌子上是一种非常过时的做法,你这样做有什么特别的原因吗?我强烈建议你不要这样做。另外,您提供的小提琴似乎工作得非常好。您的小提琴工作得很好,有什么问题吗?@Rorymcrossan是的,我不选择更改表单的方式(DOM结构)。我只能添加CSS/脚本,使其在DOM结构中工作。尝试单击顶星上的第二星和第四星rating@SoniVimal最差的明星级别运行良好。我希望顶部的星级也能像这样工作。尝试单击顶部星级中的2和4为什么需要将其存储在表中?因为,onmouse leave星级似乎无法撤消。$this.find(“td”).removeClass(“on”);将else语句更改为this