I've just started learning jQuery. And below is the code that i tried for attaching the events "mouseover" and "mouseout" for the div elements added dynamically. But when I tried running this in browser, i got no results. I dont know what is goin wrong... I hit a search for the use and syntax of using .on() of jquery and no favourable results.. Can anyone tell me, how to make my below code work?..
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function(){
$("#divid").on("mouseover",".test", function(){
$(this).css("background-color", "blue");
}).on("mouseout",".test", function(){
$(this).css("background-color", "white");
});
});
function AddBox(){
var div = $("<div></div>").addClass("test").text("Another box");
$("#divTestArea1").append(div);
}
</script>
</head>
<body>
<div id="divTestArea1">
<a href="javascript:void(0);" onclick="AddBox();">Add box</a>
<div class="test" id="divid">This is a colored box</div>
</div>
</body>
</html>
Thanks in Advance...;-)
problem here,
you are adding dynamic div to #divTestArea1
here $("#divTestArea1").append(div);
but you are delegating your event to #divid
so this search for div class test inside <div id=divid>
which is not there.
try this
$("#divTestArea1").on("mouseover",".test", function(){
....
}
with this, you are delegating the mouseover event of .test
div to#divTestArea1
..which is what we need.. and should work...
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加