当用户输入搜索词时,我使用 jQuery 从 php 类加载搜索结果。问题是jQuery在主页面第一轮按要求运行和执行功能,但是当用户输入搜索关键字并且结果通过ajax从同一页面的类文件加载时,jQuery不执行需要的功能。
我想做的是,当搜索结果加载到主页上时,它应该只显示引用和作者,而不是阿拉伯语和引用。当用户点击 Quote 时,它应该像 Accordion 一样,切换阿拉伯语和引用的 div 容器。
但是,虽然 jQuery 从类文件中加载结果非常有效,但它不会在加载搜索结果时执行隐藏阿拉伯语和引用的容器,也不会在用户单击报价时运行单击事件显示容器,如 Firebug 所示。
索引.php:
<script type="text/javascript">
$(function() {
$(".bsearch")
.keydown(function() {
//create post data
var postData = {
"search" : $(this).val()
};
//make the call
$.ajax({
type: "POST",
url: "quotes_in.php",
data: postData, //send it along with your call
success: function(response){
$("#left").html(response);
}
});
}),
$("div#smore").hide();
//toggle the componenet with class msg_body
$("p#s_quotes").click(function()
{
$(this).next("div#smore").slideToggle(200);
}),
});
</script>
<!-- Begin Left Column -->
<div id="left">
</div>
<!-- End Left Column -->
Quotes_in.php:
include_once "inc/class.quotes.inc.php";
$quotes = new Quotes($db);
if (isset($_POST['search']))
$quotes->searchQuotes();
类文件中格式化搜索的函数:
---SQL QUERY for SEARCH---
public function formatSearch($row, $search)
{
return "<div class=\"swrap\">"
. "<p id=\"s_quotes\"> " . $cQuote . " </p>"
. "<div id=\"smore\"><p id=\"s_arabic\">" . $this->h($row['cArabic']) . "</p>"
. "<p id=\"s_reference\"><span class=\"source\">Source:</span> " . $this->h($row['vReference']) . "</p></div>"
. "<p id=\"s_author\"><b>-</b> " . $this->h($row['vAuthor']) . "</p></div>";
}
最佳答案
因为你的引用元素被替换了,所以你需要使用.live()
或 .delegate()
这里的处理程序,而不是这个:
$("p#s_quotes").click(function() {
$(this).next("div#smore").slideToggle(200);
});
你需要这个:
$("p#s_quotes").live('click', function() {
$(this).next("div#smore").slideToggle(200);
});
不同于.click()
它将事件处理程序绑定(bind)到元素,该元素正在被替换...因此事件处理程序也消失了,.live()
向 document
添加一个事件处理程序,它监听来自 p#s_quotes
的点击(这可以是 just #s_quotes
) 冒泡,并在发生这种情况时执行处理程序。
对于隐藏部分,可以在 success
回调中再次调用 $("#smore").hide();
,或者将它们隐藏起来,如下所示:
<div id=\"smore\" style='display: none;'>
关于php - 当通过 ajax 调用页面时,jQuery 不会第二次运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3476724/