我试图创建一个自动完成的搜索脚本(jQuery + PHP),但是这个脚本有一个很大的问题。
我的jQuery代码是:
$(document).ready(function() {
$("#search").keyup(function() {
var search = $("#search").val();
if (search.length > 0) {
$.ajax({
type: "POST",
url: "search.php",
data: "q="+search,
dataType: "text",
cache: false,
success: function(result){
$("#autocomplete").fadeIn("fast");
$("#autocomplete").html(result);
}
});
}
});
$("#autocomplete").click(function() {
var complete = $(this).attr("title");
alert(complete);
$("#search").focus();
});
});
PHP代码:
<?php
include("config.php");
header("Content-type: text/html; charset=UTF-8");
$search = $_POST['q'];
if(mb_strlen($search, "UTF-8") > 0) {
$query = "SELECT * FROM `search` WHERE `title` LIKE '%$search%' ORDER BY `title` ASC";
$result = mysql_query($query) or die(mysql_error());
$num = mysql_num_rows($result);
if($num == 0) {
echo "Няма резултати";
}
else {
while ($row = mysql_fetch_assoc($result)) {
echo "<a href=\"javascript:void(0)\" class=\"link\" title=\"{$row['title']}\">{$row['title']}</a> <br />";
}
}
}
?>
但错误在jQuery中,因为它无法获取链接的attr("title")
...
请帮助并为我的英语道歉:)
发布于 2010-12-18 13:14:34
由于您的链接是动态的,因此需要使用.live
方法。您还希望针对单个链接,而不是容器(我假设autocomplete
是.link
锚点的容器)。
$("#autocomplete .link").live("click", function() {
var complete = $(this).attr("title");
alert(complete);
});
https://stackoverflow.com/questions/4476625
复制相似问题