问题
I jQuery autocomplete plugin for a movie search. Each movie gets an id of which is from IMDb's ID. Now the way I parse that ID is from PHP and is enclosed inside a span with class="imdbID". So it looks something likes this:
<li>Movie title 1<span class="imdbID">tt345813</span></li>
<li>Movie title 1<span class="imdbID">tt346413</span></li>
<li>Movie title 1<span class="imdbID">tt789675</span></li>
<li>Movie title 1<span class="imdbID">tt185858</span></li>
and goes on. Here's how it looks with a real example: http://www.screenr.com/aH0s
Now, I want to select a movie and alert that imdbID value.
If I use this method:
select:function(a,b){
var bbbb = $(".imdbID").text();
alert(bbbb);
}
I get all the span's value like this:

So my question is, how can I get only the .imdbID of the selected autocomplete value?
Thank you
回答1:
Referencing your other question for the PHP code, I would do something like this (please take with a grain of salt, I do not know PHP):
$tmdb = new TMDb($api_key);
$json = json_decode($tmdb->searchMovie($_GET['term']));
$response = array();
$i=0;
foreach($json as $movie){
if(!$movie->imdb_id || $movie->adult) continue;
if($i >= 6) break;
$response[$i]['value'] = $movie->name;
$response[$i]['label'] = $movie->name . ' <small>(' . date('Y',strtotime($movie->released)).')</small><span><span> (' . $movie->imdb_id . ')';
$response[$i]['imdbid'] = $movie->imdb_id;
$i++;
}
echo json_encode($response);
The idea being that you add imdbid
as a property of the JSON payload you're sending to the client.
Then on the select event:
$("input").autocomplete({
/* snip */
select: function (event, ui) {
alert(ui.item.imdbid); // <-- alert the imdbid property
}
});
回答2:
The callback receives two arguments function(event, ui)
. e.originalEvent should give you the click event that triggered the select event, along with its target ul
.
$(e.originalEvent.target).find(".imdbID").text(); //Gets you the IMDB key
来源:https://stackoverflow.com/questions/7745577/jquery-autocomplete-on-select-alert-a-value-of-which-is-in-the-suggestions