1

我正在尝试编写一个非常简单的实时搜索数据库中一些食物的代码。到目前为止一切顺利,我从 2 天以来一直在尝试为我的输入值获取正确的内容。想象一下我的意思,这是一张图片:

描述,应该如何

这是我的代码:

$(document).ready(function(e) {
	$("#search").keyup(function()
	{
		$("#here").show();
		var x = $(this).val();
		$.ajax(
		{
			type:'GET',
			url:'search.php',
			data:'q='+x,
			success:function(data)
			{
				$("#here").html(data);
			}
		});	
	});
	
	$( "#here" ).click(function() {
		var index = $("#here a").index();
		
		var content = $("#here a:nth-child(" + index + ")").text();
		$('#search').val(content);
		$( "#here" ).css( "display", "none" );
    });
  
    $( "#here" ).css( "display", "none" );
});
#here{
	width:400px;
	height: 300px;
	border: 1px solid grey;
	display: none;
}

#here a{
	display: block;
	width: 98%;
	padding: 1%;
	border-bottom: 1px solid grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1> Live Search!!!</h1>
<input type="search" name="search" id="search">
<div id="here"><div>

这是我的php代码:

<?php

if(!empty($_GET['q']))
{
	$index = 1;
	include 'connect.php';
	$q=$_GET['q'];
	$query="select * from Nahrungsmittel WHERE Name like '%$q%'";
	$result=mysqli_query($conn, $query);

	while($output=mysqli_fetch_assoc($result))
	{
		echo '<a>',$output['Name'].'</a>';
		$index++;
	}
}
?>

我尝试使用 jquery index() 函数获取第 n 个子编号。但它并没有真正起作用。

有人知道为什么吗?将非常感谢。

4

1 回答 1

1

改变这个:

var index = $("#here a").index();

对此:

var index = $(this).index();

基本上你在#here中获取每个“a”的索引,而不是你实际点击的那个

于 2016-05-20T16:08:13.130 回答