事件不会触发动态生成的元素

时间:2017-05-19 11:46:27

标签: javascript jquery javascript-events

我有一个表,在该表中,我在每行的第一列中给用户一个按钮以删除该行,并且当用户在第一列上输入鼠标时动态生成该删除按钮,这是代码

$('table').on('mouseover', "td.y-id", function () {
     $(this).append($('<a class="dlt-x" style="float: right; cursor: pointer; cursor: hand;"> <i class="fa fa-trash"></i> </a>'));
});
$('table').on('mouseleave', "td.y-id", function () {
    $('.dlt-x').remove();
});

我注册了一个事件来点击这样的删除按钮

$('table').on('click', 'a.dlt-x', function () {
  alert("clicked");
});

并且此事件未触发。我看其他类似的问题并尝试所有解决方案找到相关的委托绑定但无法解决问题。

3 个答案:

答案 0 :(得分:2)

如果要触发动态元素。使用如下

<form>
  <input type="radio" name="gender" value="male" checked />Ram's Home<br>
  <input type="radio" name="gender" value="female" />Sam's Home<br>
  <input type="radio" name="gender" value="other" />Dam's Home  
</form>

答案 1 :(得分:1)

如果不存在,则停止追加相同的元素追加

&#13;
&#13;
$(function() {
  $('table').on('mouseover', "td.y-id", function (e) {
      if ($('.dlt-x').length === 0) {
        $(this).append($('<a class="dlt-x" style="float: right; cursor: pointer;">X</a>'));
      }
  });
  
  $('table').on('mouseleave', "td.y-id", function () {
      $('.dlt-x').remove();
  });
  
  $('table').on('click', 'a.dlt-x', function () {
    alert("clicked");
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td class='y-id'>1</td>
  </tr>
  <tr>
    <td class='y-id'>2</td>
  </tr>
</table>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

将事件监听器更改为ValueErrorTraceback (most recent call last) <ipython-input-5-9121500407b3> in <module>() 4 with open(fp) as file_object: 5 contents=file_object.read() ----> 6 tiles=ttt.tokenize(contents) 7 filename='e:/collection.txt' 8 with open(filename,'a') as file_object: C:\Users\Dennis\Anaconda2\lib\site-packages\nltk\tokenize\texttiling.pyc in tokenize(self, text) 111 if wi[0] not in self.stopwords] 112 --> 113 token_table = self._create_token_table(tokseqs, nopunct_par_breaks) 114 # End of the Tokenization step 115 C:\Users\Dennis\Anaconda2\lib\site-packages\nltk\tokenize\texttiling.pyc in _create_token_table(self, token_sequences, par_breaks) 238 except StopIteration: 239 raise ValueError( --> 240 "No paragraph breaks were found(text too short perhaps?)" 241 ) 242 for ts in token_sequences: ValueError: No paragraph breaks were found(text too short perhaps?) 。否则,如果你将鼠标移到里面,你将继续附加该元素。

&#13;
&#13;
mouseenter
&#13;
$('table').on('mouseenter', "td.y-id", function() {
  $(this).append($('<a class="dlt-x" style="float: right; cursor: pointer; cursor: hand;"> <i class="fa fa-trash"></i> </a>'));
});
$('table').on('mouseleave', "td.y-id", function() {
  $('.dlt-x').remove();
});

$('table').on('click', 'a.dlt-x', function() {
  alert("clicked");
});
&#13;
&#13;
&#13;