jQueryでグレーディングシステムを作成する必要があります(1つの円をクリックすると、それ以前の円は緑色になります)。他のボタンを押した後にjQueryで「クリック」機能が動作しないのはなぜですか?
空の円をクリックすると、その円と前の円が緑色になります。
[最大値を更新]ボタンをクリックした場合、入力ボックスに円の数を書き込んだ場合、希望する円の数が表示されますが、後でそのサークルの1つをクリックすると、彼らはクラスrating-circle
を持っています。
どうしてですか?
私のコードは以下の通りです。
$(function() {
//this function is drawing circles
var makingCircles = function(numberOfStars) {
$("#rating-container").empty();
for (let i = 0; i < numberOfStars; i++)
$('<div class="rating-circle"></div>').appendTo('#rating-container');
}
var chosenGrade = null;
var numberOfStars = $("#rating-container").attr("max-value");
makingCircles(numberOfStars); // this is for initial drawing of circles
$("#update-max-value").on("click", function() {
numberOfStars = $("#max-value").val();
makingCircles(numberOfStars);
});
$(".rating-circle").click(// this function is for rating
function() {
chosenGrade = $(this);
chosenGrade.addClass("rating-chosen");
chosenGrade.prevAll().addClass("rating-chosen");
});
});
body {
font-family: Verdana;
}
h1,
h2,
h3 {
color: darkblue;
}
.rating-circle {
height: 2em;
width: 2em;
border: .1em solid black;
border-radius: 1.1em;
display: inline-block;
margin: 0.3em;
padding: 0.1em;
}
.rating-hover {
background-color: yellow;
}
.rating-chosen {
background-color: green;
}
<h2>Finding elements using jQuery</h2>
<div>This session is about identifying elements using jQuery methods and selectors.</div>
<h3>Rate this session</h3>
<div id="rating-container" max-value="5">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label for="max-value">Enter max value:</label>
<input type="text" id="max-value" />
<button type="button" id="update-max-value">Update max value</button>
</div>
を補充するたびにjqueryのイベントを見て、イベントハンドラをクリックしバインドする必要がありますので
委任。 –
イベントの委任を使用してコードを修正するフィドルを作成しました。 https://jsfiddle.net/9z5vdr8w/レートを下げて再評価したい場合のバグを修正しました(たとえば、5つのサークルを選択して4に変更したい) – Paker