每次执行此代码块的“成功”功能时,都会发生一些不需要的事件:
如果我不刷新浏览器并再次输入相同的名称,则会显示重复的图像。每次运行代码时都会发生这种情况。
如果我没有刷新浏览器并输入一个不存在的名称,那么在搜索返回一个名称之前,这两个图像都显示在页面上。
如何停止复制?我在jQuery中查看了.append的替代方法,但没有一个具有所需的结果。
我想我每次运行时都需要重置查询,否则看起来这也会导致并发症。
var friendName;
function findFriend() {
friendName = $('#friendsearch').val();
console.log(friendName);
var query = new Parse.Query(Parse.User);
query.equalTo("username", friendName); // find users that match
query.find({
success: function (friendMatches) {
// This section is always run, no matter the outcome. Depending on the input depends on which result is shown
if (friendMatches.length === 0)
// console.log('NO MATCH FOUND!!!');
$(".no_user").show();
else // Query executed with success
imageURLs = [];
for (var i = 0; i < friendMatches.length; i++) {
var object = friendMatches[i];
imageURLs.push(object.get('pic'));
}
// If the imageURLs array has items in it, set the src of an IMG element to the first URL in the array
for (var j = 0; j < imageURLs.length; j++) {
$('#imgs').append("<img src='" + imageURLs[j] + "'/>");
}
console.log('MATCH FOUND!!!');
},
// Only if the code breaks and cannot either find or not find a user should this error be returned
error: function (error) {
alert('Opps we have a problem' + error.message);
}
});
}
// This captures the users input and is triggered when the user presses the find
$('#find_button').click(function (e) {
findFriend();
});
答案 0 :(得分:0)
您需要在添加新图像之前删除旧图像:
$('#imgs').empty();
何时清除是另一个问题(我认为这是你'不想要的事件#2'):
success: function (friendMatches) {
// clear images first, so that previous search results
// don't show when the current search returns 0 results
$('#imgs').empty();
...
}