SlideToggle 不适用于动态生成的 div
我想添加很多
带有滑动切换的隐藏div。我不想写这么长的代码,这就是我尝试这个的原因:
<html>
<head>
<script type="text/javascript" src="jquery-1.5.2.js"></script>
<script type="text/javascript" >
</script>
<script type="text/javascript">
$(document).ready(function() {
//this function does not work when I append the p and div
$(".flip").click(function() {
$(this).next().slideToggle("slow");
});
var p = $('<p></p>').addClass('flip').text('click here');
var div = $('<div></div>').addClass('panel').text('hellow world');
p.append(div);
$(p).bind('click', function() {
// alert($(this).text()); //this alert works when i put it as a p.bind
$(this).next().slideToggle("slow"); //this does not work!! but the previous alert does work....
});
$("div#elements").append(p);
});
</script>
<style type="text/css">
div.panel,p.flip
{
margin:0px;
padding:5px;
text-align:center;
background:#e5eecc;
border:solid 1px #c3c3c3;
}
div.panel
{
height:120px;
display:none;
}
</style>
</head>
<body >
<div id="elements" >
</div>
</body>
</html>
有趣的是 $(flip) 函数不适用于生成的 p 和 div...然后我将该函数添加为 (p ).bind,并尝试使用警报,它确实有效,但是当我想滑动切换时,它不起作用,有人知道为什么吗?
I want to add a lot of
with hidden divs that slideToggle. I don't want to write such a long code that's why I'm trying this:
<html>
<head>
<script type="text/javascript" src="jquery-1.5.2.js"></script>
<script type="text/javascript" >
</script>
<script type="text/javascript">
$(document).ready(function() {
//this function does not work when I append the p and div
$(".flip").click(function() {
$(this).next().slideToggle("slow");
});
var p = $('<p></p>').addClass('flip').text('click here');
var div = $('<div></div>').addClass('panel').text('hellow world');
p.append(div);
$(p).bind('click', function() {
// alert($(this).text()); //this alert works when i put it as a p.bind
$(this).next().slideToggle("slow"); //this does not work!! but the previous alert does work....
});
$("div#elements").append(p);
});
</script>
<style type="text/css">
div.panel,p.flip
{
margin:0px;
padding:5px;
text-align:center;
background:#e5eecc;
border:solid 1px #c3c3c3;
}
div.panel
{
height:120px;
display:none;
}
</style>
</head>
<body >
<div id="elements" >
</div>
</body>
</html>
Interesting thing is that the$(flip) function DOES not work with the generated p and div...I then added the function as a (p).bind, and tried it with an alert and it DOES work, but when I want to slideToggle, it doesn't work, does anybody know why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
那是因为您的 p 和 div 元素是动态添加的,并且在加载页面时还不是 DOM 的一部分。您是否尝试过使用 jQuery live API 来代替?
That's because your p and div elements are dynamically added and are not part of the DOM yet when the page is loaded. Have you tried using the jQuery live API instead?