问题
I need help. I can't find my mistake. For some reason I get duplicate li when I append a ul. I created an AJAX search that searches for results upon keyup. The problem is that when I leave the page, for example if I click on profile and come back, if I search the same keyword, I get duplicate results. Which is very weird because I empty() my ul before typing anything in. It might be something very simple but I cannot find it.
Here is my jQuery that appends my ul:
$(document).delegate("#search", "pageshow", function() {
$("#search input").focus(function() {
$("ul#search_list").empty();
$(this).val("");
localStorage.search = "";
});
$("#search input").keyup(function() {
$("ul#search_list").empty();
localStorage.search = $("#search input").val();
var result = "";
$.ajax({
url: '/app/users/search/'+localStorage.search,
dataType: 'jsonp',
jsonp: 'jsoncallback',
success: function(data) {
$.each(data, function(i,item){
var result = '<li><a href="#friend_profile" class="friend_profile" data-search_user_id="'
+ item.id +
'"><img class="round" src="'
+ item.picture + '" /><h3>'
+ item.name +
'</h3><p>' + item.location + '</p></a></li>';
$("ul#search_list").append(result);
$("ul#search_list").listview('refresh');
});
},
error: function(){
$("ul#relationships_list").text('Sorry, you dont seem to have any friends.');
}
});
});
});
Here is the HTML ul that is being appended:
<div data-role="page" id="search">
<div data-role="header" data-position="fixed">
<a data-rel="back">Back</a>
<h1>Search</h1>
<a href="index.html">Settings</a>
</div><!-- /header -->
<div data-role="content">
<ul id="search_list" data-role="listview" data-filter="true">
</ul>
</div><!-- /content -->
<div data-role="footer" data-position="fixed">
<div data-role="navbar">
<ul>
<li><a href="#dash" data-icon="grid">Dash</a></li>
<li><a href="#points" data-icon="star">Points</a></li>
<li><a href="#claim" data-icon="check">Claim</a></li>
<li><a href="#search" data-icon="search" class="ui-btn-active ui-state-persist">Search</a></li>
<li><a href="#profile" data-icon="home">Profile</a></li>
</ul>
</div>
</div><!-- /content -->
</div><!-- /page -->
Here is a screenshot of what appears. In case you want the visual:
Thanks everyone!
回答1:
I had that issue once where I cleared the results on page hide. I'm not sure what version of JQueryMobile you're using, but I had this issue in 1.0. The ajax event doesn't seem to destroy the page on pagehide, so I had to remove the elements on pagehide. I don't know if this helps.
回答2:
None of these options worked. But I found a quick fix that removes duplicates in a ul. It is the only thing that has worked so far. Here is a link to the solution:
jquery remove duplicate li
来源:https://stackoverflow.com/questions/10399510/jquery-append-json-data-in-a-jquery-mobile-list-adding-duplicates-when-page-i