我希望能够将<div class="rate">Rate this product</div>
替换为Bad, Better, Best
的评级描述之一,以此类推,当用户将鼠标悬停在评级上时,让评级描述停留在用户单击评级时。我对Jquery还是很陌生,所以我不知道从哪里开始。
的HTML
<form action="" method="post">
<ul>
<li id="rate-1">
<label for="rating-1"><input type="radio" value="1" name="rating" id="rating-1" />1 star</label>
</li>
<li id="rate-2">
<label for="rating-2"><input type="radio" value="2" name="rating" id="rating-2" />2 stars</label>
</li>
<li id="rate-3">
<label for="rating-3"><input type="radio" value="3" name="rating" id="rating-3" />3 stars</label>
</li>
<li id="rate-4">
<label for="rating-4"><input type="radio" value="4" name="rating" id="rating-4" />4 stars</label>
</li>
<li id="rate-5">
<label for="rating-5"><input type="radio" value="5" name="rating" id="rating-5" />5 stars</label>
</li>
</ul>
<div class="rate">Rate this product</div>
</form>
说明
<div>Bad</div>
<div>Better</div>
<div>Best</div>
<div>Great</div>
<div>Good</div>
最佳答案
试试jQuery(使用小提琴https://jsfiddle.net/cwymmznw/):
// HTML
<form action="" method="post">
<ul>
<li id="rate-1">
<label for="rating-1"><input type="radio" data-desc="Bad" value="1" name="rating" id="rating-1" />1 star</label>
</li>
<li id="rate-2">
<label for="rating-2"><input type="radio" data-desc="Good" value="2" name="rating" id="rating-2" />2 stars</label>
</li>
<li id="rate-3">
<label for="rating-3"><input type="radio" data-desc="Great" value="3" name="rating" id="rating-3" />3 stars</label>
</li>
<li id="rate-4">
<label for="rating-4"><input type="radio" data-desc="Better" value="4" name="rating" id="rating-4" />4 stars</label>
</li>
<li id="rate-5">
<label for="rating-5"><input type="radio" data-desc="Best" value="5" name="rating" id="rating-5" />5 stars</label>
</li>
</ul>
<div class="rate">Rate this product</div>
</form>
// JS
$('input').hover(function(e) {
$('.rate').text($(this).attr('data-desc'));
}, function(e) {
if ($('.selected')) {
$('.rate').text($('.selected').attr('data-desc'));
} else {
$('.rate').text('Rate this product');
}
});
$('input').click(function(e) {
$('.rate').text($(this).attr('data-desc'));
$('.selected').removeClass('selected');
$(this).addClass('selected');
});