【发布时间】:2016-05-01 02:56:29
【问题描述】:
我想创建一个搜索框,在输入搜索短语时只显示匹配的条目;与此处描述的功能相同:
How to perform a real time search and filter on a HTML table
不同之处在于,我拥有的表是从 PHP 循环和 SQL 数据创建的。但是,我不确定如何采用适合我的代码。
个人认为可能与“//打印表格行”部分有关。
代码如下:
var $search_rows = $('#table tr');
$('#search').keyup(function() {
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$search_rows.show().filter(function() {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
<html>
<script src="./jquery-1.6.4.js"></script>
<script src="./sorttable.js"></script>
<script src="./searchbox.js"></script>
<link rel="stylesheet" href="styles.css">
<head>
<title>Tau Empire Cadre Census</title>
</head>
<body>
<?php
//// //// //// ////
// DATABASE
//// //// //// ////
//database credentials
$db_host="localhost";
$db_user="tau";
$db_pwd="kuhohNg3";
$db="tau_census";
$db_table="cadres";
//make the connection
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($db))
die("Can't select database");
// sending query
$result = mysql_query("SELECT * FROM {$db_table}");
if (!$result) {
die("Query to show fields from table failed");
}
//assign a variable the number of returned table fields
$fields_num = mysql_num_fields($result);
//// //// //// ////
// HEADING
//// //// //// ////
echo "<h1>Tau Empire Cadre Census</h1>";
// Search box
echo '<input type="text" id="search" placeholder="Type to search">';
//// //// //// ////
// TABLE
//// //// //// ////
//create the table, and use the JS sortable script
echo '<table id="table" class="sortable"><tr>';
// printing table headers
echo "<td class=headings>Designation</td>";
echo "<td class=headings>Location</td>";
echo "<td class=headings>Founding</td>";
echo "<td class=headings>Commanding Officer</td>";
echo "<td class=headings>Current Status</td>";
echo "<td class=headings>Current Location</td>";
echo "<td class=headings>Mission</td>";
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// For each field print the content
for($i=1; $i<$fields_num; $i++) {
echo "<td>" . $row[$i] . "</td>";
}
echo "</tr>";
}
echo "</table>";
mysql_free_result($result);
?>
</body>
</html>
运行它不会引发任何错误,但它也不起作用。这需要比我更大的大脑才能解决,拜托。
【问题讨论】:
-
您在浏览器控制台中看到了什么?有任何错误信息吗?你加载了哪个版本的 jQuery 库?您的代码是否包含在
$(document).ready()或$(function(){...});中? -
您的代码没有正确关闭您的单元格-
</td->echo "<td>$row[$i]</td"; -
控制台没有错误,实际上什么也没有。我不确定 jQuery 库是如何工作的,所以不知道如何找到它。我所知道的只是 HTML 中的内容; jquery-1.6.4.js。我没有包装代码,但确实尝试了你的建议,但都没有解决问题;也没有产生任何错误。
-
<table>元素结束标记在哪里? -
所以你的
<head>中有<script src="...jquery-1.6.4.min.js"></script>之类的东西?
标签: javascript php html mysql search