Bind scroll Event To Dynamic DIV?

2020-02-07 00:33发布

For example, after using AJAX, I'll have a scrollable DIV. How to bind scroll events to it?

I've tried:

$(window).on("scroll", ".mydiv", function(){...})
$(document).on("scroll", ".mydiv", function(){...})
$(".mydiv").on("scroll", function(){...})
$(".mydiv").scroll(function(){...})

But they didn't work.

DEMO

9条回答
ら.Afraid
2楼-- · 2020-02-07 01:01

I'm having the same issue and I've found the following in the jQuery .on() API:

In all browsers, the load, scroll, and error events (e.g., on an element) do not bubble. In Internet Explorer 8 and lower, the paste and reset events do not bubble. Such events are not supported for use with delegation, but they can be used when the event handler is directly attached to the element generating the event.

So unfortunately this doesn't appear to be possible.

查看更多
孤傲高冷的网名
3楼-- · 2020-02-07 01:07

try this modified from your code

http://jsfiddle.net/apDBE/

$(document).ready(function(){

    // Trigger
    $("#btn").click(function(){
        if ($(".myDiv").length == 0) // Append once
        $("body").append('<div class="myDiv"><br><br><p>Content1<p><br><br><p>Content2<p><br><br></div>');
    });

    // Not working
    $(".myDiv").scroll(function(){
        alert("A");
    });

    // Not working
    $(document).on("scroll", ".myDiv", function(){
        alert("A");
    });
});

Hope this help

查看更多
一夜七次
4楼-- · 2020-02-07 01:10

It's work by attaching on directly, check example bellow.

Hope this helps.

$("body").append('<div class="myDiv"><br><br><p>Content1<p><br><br><p>Content2<p><br><br></div>');

$(".myDiv").on("scroll", function(){
  	 console.log("scrolling");
});	
	body{ font-family: tahoma; font-size: 12px; }
	
	.myDiv{
		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>

查看更多
登录 后发表回答