on scroll事件没有绑定动态添加的元素Jquery

时间:2015-09-05 11:36:38

标签: jquery scroll

我正在动态添加一个类名为<div>的{​​{1}}元素,我希望实现的是在此div内发生requirement事件时执行我的功能。

HTML

scroll

的jQuery

<div class="scroll requirement" >

1 个答案:

答案 0 :(得分:1)

这很奇怪,我猜是因为这个事件经常发生。如果它在创作时反弹就有效......

$(document).ready(function(){
	$('#add').click(function(){
      $('body').append('<div class="scroll requirement" ><br><br><br><br><br><br><br><br><br><br><br><br><br></div>');
      $('.requirement').on('scroll',function(){alert("hello")});
    });
 });
/*.pane{
    min-height:2000px;
    min-height:400px;
   
}
.requirement{
    max-height:100px;
     overflow:scroll;
}
}*/

		body{ font-family: tahoma; font-size: 12px; }
	div.requirement{
		height: 90px;
		width: 300px;
		border: 1px solid;
		background-color: lavender;
		overflow: auto;
	}
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    </head>
<body>
<div class="scroll requirement" >
<br><br><br><br><br><br><br><br><br><br><br><br><br>
</div>

<button id="add">Add another pane</button>
  </body>
  </html>

然而

内联绑定有效......

$(document).ready(function(){
	$('#add').click(function(){
      $('body').append('<div class="scroll requirement" onscroll="scrollHandler()" ><br><br><br><br><br><br><br><br><br><br><br><br><br></div>');
    //  $('.requirement').on('scroll',function(){alert("hello")});
    });

 });
    function scrollHandler(){
    alert('hello');
    }
/*.pane{
    min-height:2000px;
    min-height:400px;
   
}
.requirement{
    max-height:100px;
     overflow:scroll;
}
}*/

		body{ font-family: tahoma; font-size: 12px; }
	div.requirement{
		height: 90px;
		width: 300px;
		border: 1px solid;
		background-color: lavender;
		overflow: auto;
	}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="scroll requirement" onscroll="scrollHandler()" >
<br><br><br><br><br><br><br><br><br><br><br><br><br>
</div>

<button id="add">Add another pane</button>
  </body>