我在使用 jquery 和 ajax 使页面正常工作时遇到问题。我试图让这个例子尽可能简单。 jquery 在单个页面上时可以工作,但在调用后我无法让它工作。
2页,第一页:
<小时/><!DOCTYPE html>
<html>
<head>
<script src="../js/jquery-1.8.2.min.js"></script>
<style type='text/css'>
#one {
width: 200px;
height: 200px;
background: red;
}
#two{
width: 200px;
height: 200px;
background: blue;
}
.show {
display: none;
background: yellow;
}
</style>
<script>
$(document).ready(function() {
$("button").click(function() {
$("#div1").load("definition.jsp");
});
});
</script>
<script type="text/javascript">
$('#wrapper').on('mouseenter', '.touch', function() {
$(this).next('.show').fadeIn(800);
}).on('mouseleave', '.touch', function() {
$(this).next('.show').delay(800).fadeOut(800);
});
</script>
</head>
<body>
<div id="div1"><h2>jQuery AJAX Test</h2></div>
<button>Get External Content</button>
</body>
第二页:
<div id="wrapper">
<div id="parent_one">
<div class="touch" id="one">Enter</div>
<div class="show">Works</div>
</div>
<div id="parent_two">
<div class="touch" id="two">Enter</div>
<div class="show">Second Works</div>
</div>
有什么想法吗?请帮忙!
最佳答案
您无法将事件绑定(bind)到 #wrapper
因为当页面加载时它不存在。相反,将其绑定(bind)到 document
,并附有查找 #wrapper .touch
的说明。仅当该元素添加到 DOM 后才会触发该事件。
更改第二个 <script>
中的内容标记为:
$(document).on('mouseenter', '#wrapper .touch', function() {
$(this).next('.show').fadeIn(800);
}).on('mouseleave', '#wrapper .touch', function() {
$(this).next('.show').delay(800).fadeOut(800);
});
Read what the jQuery API has to say about .on()
.
注意:如果将事件绑定(bind)到 #div1
,它将触发任何和所有 .touch
您放入其中的元素,而不仅仅是 #wrapper
中的元素.
关于Jquery 不适用于 ajax 加载的内容 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18793215/