jQueryの検索で、ユーザーから検索語を取得し、php経由でmySQL DBに照会して、divを(Flashcardのような質問と回答で)読み込みます。これは完璧に機能します。また、「回答」という単語がクリックされるまで、jQueryトグル機能を使用して回答を非表示にしています。これは、スタンドアロンとして、そしてHTMLページ上のテキストですでにうまく動作しますが、div idなどはうまくいくように見えますが、検索から入力されたテキストに対しては機能しません。何とかトグル機能は検索されたテキストに作用できません。jQueryが「インスタント検索」の後で切り替えることができません
HTML::search.js
$('#search').keyup(function() {
var search_term = $(this).val();
$.post('php/search.php ', { search_term: search_term}, function(data){
$('#search_results').html(data);
});
});
$(document).ready(function() {
$('#commentbox').hide();
$('a.comment').click(function() {
var id = $(this).attr('id');
$('#commentbox' + id).toggle(200);
return false;
});
});
PHP:search.php
<?php
require 'connection.php';
if (isset($_POST['search_term'])){
$search_term = mysql_real_escape_string(htmlentities($_POST['search_term']));
if (!empty($search_term)) {
$search = mysql_query("SELECT `question`, `ans1` FROM `quiz` WHERE `question` LIKE '%$search_term%'");
$result_count = mysql_num_rows($search);
$suffix = ($result_count != 1) ? 's' :'';
echo '<p>Your search for <strong>' , $search_term, '</strong> returned <font color="red"><strong>' , $result_count, '</strong></font> result', $suffix , '</p>';
echo '<div id="wrap">';
$i=0;
while ($results_row = mysql_fetch_assoc($search)) {
echo '<p>' , $results_row['question'] ,' </p>';
echo '<div class="explain"><a href="#" id="',$i,'" class="comment">Answer</a></div>';
echo '<p><div id="commentbox',$i ,'" class="commentbox" style="display:none">',$results_row['ans1'],'</div></p>';
$i=$i+1;
}
}
}
?>
<html lang="en">
<head>
<meta charset = "utf-8">
<title> JQ Instant Search</title>
<link rel ="stylesheet" type = "text/css" href = "css/style.css">
</head>
<body>
Start Search: <input id = "search" type = "text"/>
<div id="search_results"></div>
<script type="text/javascript" src = "js/jquery.js"></script>
<script type="text/javascript" src = "js/search.js"></script>
<h4 id="question1">Question 1 - Which animal barks?</h4>
<ol>
<li>1. Giraffe </li>
<li>2. Worm </li>
<li>3. Dog </li>
</ol>
<div class="explain"><a href="#" id="b" class="comment">Answer</a></div>
<div id="commentboxb" class="commentbox" style="display:none">The answer is 3. Anyone should know this</div>
</body>
</html>
JSのindex.phpここでは、コードです
MySQLの表:クイズ
question *ans1
what sound do cows make? moo
where is London? England
What is the negative cube root of e^-3? obvious
おかげになるだろう! FYI - 何らかの理由で 'on'は機能しませんが、 'live'は問題を解決します。 – CLS
jQuery 1.7の時点で、.live()メソッドは推奨されなくなりました。 –