我在处理以下问题时遇到困难。
我有一个页面,其中列出了某些用户当前关注的人。在同一页面中,还有一个字段用于搜索新联系人。使用AJAX,此搜索的结果将显示在已跟踪联系人的同一位置。
两种类型的人(已经关注一次,并且由AJAX返回一次)都有关注/取消关注按钮。
问题是此按钮不适用于AJAX返回的联系人。
这是处理此问题的部分代码:
$(document).ready(function (){
// ---------- contact search --------------
$("#searchContacts").keyup(function(event){
if (event.keyCode == 13){
document.getElementById('fillText').innerHTML = "";
var searchValue = $("#searchContacts").val();
var userID = $("#userID").text();
if (searchValue != ""){
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status == 200){
document.getElementById('fillText').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","searchContacts_server.php?contact="+searchValue+"&userID="+userID,true);
xmlhttp.send();
}
}
});
// ---------- follow user -------
$(".followButton").click(function(){
var userIDToFollow = $(this).attr('name');
var userID = $("#userID").text(); // getting userId from hidden filed on the page
if (window.XMLHttpRequest){
xmlhttpAdd = new XMLHttpRequest();
} else {
xmlhttpAdd = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttpAdd.onreadystatechange = function(){
if (xmlhttpAdd.readyState==4 && xmlhttpAdd.status == 200){
$("input[name='"+userIDToFollow+"']").val('Following');
}
}
xmlhttpAdd.open("GET","followContacts_server.php?userIDToFollow="+userIDToFollow+"&userID="+userID,true);
xmlhttpAdd.send();
});
});
使用事件委托,以便事件委托AJAX
也可以工作:
改变:
$(".followButton").click(function(){
到:
$(document).on("click", ".followButton", function(){
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句