jQuery ->
  $(".comment-form, .reply-form")
    .on "ajax:beforeSend", (evt, xhr, settings) ->
      debugger;
      $(this).find('textarea')
        .addClass('uneditable-input')
        .attr('disabled', 'disabled');
    .on "ajax:success", (evt, data, status, xhr) ->
      debugger;
      $(this).find('textarea')
        .removeClass('uneditable-input')
        .removeAttr('disabled', 'disabled')
        .val('');
      debugger;
      $(data.comments).hide().insertAfter($(this)).show('fast')


这应该在.comment-form.reply-form div中发生某些事情时运行。但是,该代码仅在.comment-form中发生某些情况时运行。

.comment-form div在页面加载时显示,但.reply-form div仅在单击“答复”按钮时出现。我认为这可能是问题所在-页面加载中不存在.reply-form,因此当它确实显示时,JQuery无法识别它。我将如何解决这个问题?

最佳答案

这是处理动态元素的侦听器的方式(例如,在ready事件之后)。



//Use delegation
$('#delegationparent').on('click', 'div', function(){
  $('#results').html('Delegated div.');
  });
//Insert new div (didn't exist before)
$('<div>Delegate Div</div>').appendTo('#delegationparent');

//No delegate
//Create Div
var div = $('<div>No Delegate Div</div>');
//Attach handler to div
div.on('click', function(){
  $('#results').html('No delegated div');
  });
//Insert Div
div.appendTo('#nodelegate');

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="delegationparent"></div>
<div id="nodelegate"></div>
<pre id="results"></div>

关于javascript - jQuery无法识别选择器中发生了什么,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32152200/

10-12 12:55
查看更多