[英]Why are my event handlers not being attached to elements created in jQuery?
I am working on a five star rating system. 我正在研究五星级评级系统。 There are five star icons. 有五个星形图标。 When an icon is clicked, I want to change the value of an input to whichever star is clicked(eg if the fourth star is clicked, the input will have a value of 4). 单击图标时,我想将输入的值更改为单击的任意一个星形(例如,如果单击第四个星形,则输入的值为4)。 My problem is that the click method that I apply to the newly created icon does not work at all. 我的问题是,我应用于新创建的图标的click方法根本不起作用。 What am I doing wrong? 我究竟做错了什么? Here is a jsFiddle to demonstrate. 这是一个jsFiddle进行演示。
html html
<div class="rating" style="float: none;clear: both;">
<noscript>
<label class="radio-inline">
<input type="radio" name="stars" value="1" title="1 Star"> 1
</label>
<label class="radio-inline">
<input type="radio" name="stars" value="2" title="2 Stars"> 2
</label>
<label class="radio-inline">
<input type="radio" name="stars" value="3" title="3 Stars"> 3
</label>
<label class="radio-inline">
<input type="radio" name="stars" value="4" title="4 Stars"> 4
</label>
<label class="radio-inline">
<input type="radio" name="stars" value="5" title="5 Stars"> 5
</label>
</noscript>
</div>
<input type="text" name="stars" value="" id="stars">
Javascript Java脚本
$element = $('.rating');
$element.empty();
for (var i = 0; i < 5; i++) {
var occurrence = i + 1;
var newStar = $('<i class="fa fa-star-o" title="' + occurrence + ' stars" data-occurrence="' + occurrence + '"></i>');
newStar.on('click', function() {
$('#stars').val(occurrence + ' stars given.');
});
$element.append(newStar);
}
$element.each(function() {
var _parent = $(this);
var originalStars = _parent.html();
$(_parent).on('mouseover', 'i[class*="fa-star"]', function() {
var starOccurrence = $(this).prevAll().andSelf().length;
$(this).prevAll().andSelf().removeClass('fa-star-o').addClass('fa-star');
}).mouseout(function() {
$(_parent).html(originalStars);
});
});
2 problems. 2个问题。 Mentioned in the comments, don't replace the inner html, just remove/add classes to reset the stars. 在评论中提及,请勿替换内部html,只需删除/添加类即可重置星标。
.mouseout(function() {
$('i').removeClass('fa-star').addClass('fa-star-o');
});
Second problem is you need to grab the occurrence value from the data attribute, and not the overwritten occurrence variable. 第二个问题是您需要从data属性中获取出现值,而不是被覆盖的出现变量。
$('#stars').val($(this).data('occurrence') + ' stars given.');
jsFiddle: https://jsfiddle.net/9mLzLsw7/2/ jsFiddle: https ://jsfiddle.net/9mLzLsw7/2/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.