为什么我的事件处理程序没有附加到jQuery中创建的元素?

时间:2016-02-22 23:46:43

标签: javascript jquery

我正在研究一个五星评级系统。有五个星形图标。单击图标时,我想将输入的值更改为单击任何一个星(例如,如果单击第四个星,则输入的值为4)。我的问题是我应用于新创建的图标的click方法根本不起作用。我究竟做错了什么?这是一个jsFiddle来演示。

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

 $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);
    });
  });

1 个答案:

答案 0 :(得分:0)

2个问题。 在评论中提到,不要替换内部html,只需删除/添加类来重置星标。

.mouseout(function() {
    $('i').removeClass('fa-star').addClass('fa-star-o');
  });

第二个问题是你需要从数据属性中获取出现值,而不是被覆盖的出现变量。

$('#stars').val($(this).data('occurrence') + ' stars given.');

jsFiddle:https://jsfiddle.net/9mLzLsw7/2/

相关问题