问题
I have been trying for days to get jquery autocomplete to work the way I need it to.
so far I have this which works fine:
<script>
$(function() {
var availableTags = [<?php
$taglist = Array();
foreach ($users as $user)
if ($user->getAttribute('first_name') == ''){
$taglist[] = '"'.$user->getUserName().'"';
}else{
$taglist[] = '"'.$user->getAttribute('first_name').' '.$user->getAttribute('last_name').'"';
}
echo join(',', $taglist);
?>];
$("#searchmem").autocomplete({
source: availableTags,
minLength: 2,
select: function(event, ui) {
$("#searchmem").val(ui.item.label);
$("#submit").click();
}
}).data("autocomplete")._renderItem = function (ul, item) {
return $("<li />")
.data("item.autocomplete", item)
.append("<a><img src='/files/avatars/1.jpg' />" + item.label + "</a>")
.appendTo(ul);
}
});
</script>
This will output the image /files/avatars/1.jpg next to the respective users username or full name.
The problem I'm having is trying to output the right users avatar. Each .jpg file corresponds with the username so I could have used $user->getUserID() in the src but this won't work because it's not inside the foreach $users as $user loop.
I have tried putting the whole autocomplete script inside the foreach which when tested did alert the right thing but autocomplete wouldn't work.
I have also tried creating two variables such as
availableTags1 = { label: .... $user->getUserName() etc... }
availableTags2 = { avatar: .... $user->getUserID() etc... }
availableTags = availableTags1 + availableTags2;
and
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li />")
.data("item.autocomplete", item)
.append("<a><img src=' + item.avatar + ' />" + item.label + "</a>")
.appendTo(ul);
}
But again this didn't work. I'm completely lost! How can I get it to output the image alongside the relevant username? Help would be much appreciated.
回答1:
In your case, you have to build an array like :
var availableTags = [
{label: '...', avatar: '...'},
{label: '...', avatar: '...'},
...
];
And use:
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li />")
.data("item.autocomplete", item)
.append("<a><img src='" + item.avatar + "' />" + item.label + "</a>") // Note the additional double quotes
.appendTo(ul);
}
(see this example on jQuery UI for using custom data)
Then, for generating you array via PHP, you should use:
<?php
$taglist = Array();
foreach ($users as $user) {
$data = array();
if ($user->getAttribute('first_name') == ''){
$data["label"] = $user->getUserName();
} else {
$data["label"] = $user->getAttribute('first_name').' '.$user->getAttribute('last_name');
}
$data["avatar"] = $user->getUserID();
$taglist[] = $data;
}
?>
var availableTags = <?php echo json_encode($taglist); ?>;
来源:https://stackoverflow.com/questions/14792661/jquery-autocomplete-with-php-foreach-generated-results