为什么响应页面(test.html)上的链接无法在主页面上调用jquery?虽然两个链接都有相同的类,但请帮助我做些什么来使它工作。
主页:
<script type="text/javascript">
$(document).ready(function () {
$(".comment_link").click(function () {
$.ajax({
url: "test.html",
success: function (cont) {
if (cont) {
$("#view" ).append(cont);
}
}
});
return false;
});
});
</script>
<div id="view"></div>
<a href="#" class="comment_link">add comment</a>
test.html的文件内容:
Helloo
<a href="#" class="comment_link">Test</a>
答案 0 :(得分:1)
您需要使用事件委派 - ,因为您要动态添加comment_link
$(document).on('click',".comment_link",function (){...});
您需要像这样更改代码 -
$(document).ready(function () {
$(document).on('click', ".comment_link", function () {
$.ajax({
url: "test.html",
success: function (cont) {
if (cont) {
$("#view").append(cont);
}
}
});
return false;
});
});
答案 1 :(得分:1)
该元素是“新”创建的,因此您必须将事件绑定到它...
使用on()
方法。 (以前是live()
但已弃用)
$('body').on('click','.comment_link',function(){..//your code here..});
所以你想把你的ajax放在一个函数中,所以你可以点击它来调用它,并将它委托给新的元素......而不需要重写代码......你不必这样做,只是让它更容易重用等
$(document).ready(function () {
//Assign click handler
$('body').on('click','.comment_link', getAjax);
//Your Ajax call put into function
function getAjax(){
$.ajax({
url: "test.html",
success: function (cont) {
if (cont) {
$("#view" ).append(cont);
}
}
});
return false;
};
});