2016-05-15 102 views
0

我已經嘗試了關於我在其他Web上找到的其他「解決方案」,但仍然無法使其工作。Jquery .on()在動態div上滾動不起作用

我有一個動態創建的div與position: fixed; overflow-y: auto,div是在用戶點擊某個鏈接時創建的。這是我用來試圖執行一些代碼的功能,只要動態創建的div滾動。

 $("#scroller").on("scroll",function() { 
      console.log("scrolled.."); 
     }); 

#scroller是動態創建的div的ID。

的事情是,這個功能不會被加載頁面時工作,但它確實工作當功能被粘貼到谷歌Chrome開發者控制檯。

我已經試過各種使用常規scroll()功能改變on()功能如下:

$("#scroller-container").on("scroll","#scroller",function() { 
     console.log("scrolled.."); 
    }); 

然而,它仍然無法正常工作。

我該如何得到這個工作?

編輯:所有的代碼是一個jQuery(window).load(function()...函數內

回答

1

嘗試結合滾動事件的元件的DOM所附後,這樣的:

$("body").on("DIVscroll", "#scroller", function(){ 
 
    console.log("Scrolled..."); 
 
}); 
 

 
$("#btn").on("click", function(){ 
 
    $("body").append('<div id="scroller">I have a dynamically created div with position: fixed; overflow-y: auto, the div is created when a user clicks a certain link. This is the function Im using to try and execute some code whenever that dynamically created div is scrolled.</div>'); 
 
    ScrollEventListener($("#scroller")); 
 
}); 
 

 
function ScrollEventListener(el){ 
 
    el.on("scroll", function(){ 
 
    el.trigger("DIVscroll"); 
 
    }); 
 
}
body{ 
 
    font-size: 17px; 
 
} 
 
\t 
 
#scroller{ 
 
    height: 100px; 
 
    width: 300px; 
 
    border: 1px solid; 
 
    overflow-y: auto; 
 
    position: fixed; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="button" id="btn" value="Append div"/>

+0

我有接受你的回答是正確的,因爲它完全起作用,並促使我解決問題!謝謝! – Ryan

+0

@Ryan不客氣。很高興幫助你.. –