【问题标题】:javascript jquery expand collapse search resultsjavascript jquery 展开折叠搜索结果
【发布时间】:2013-06-29 15:35:47
【问题描述】:

我在下面有这段代码,它可以展开和折叠搜索结果。搜索将搜索结果显示在同一页面上,因此不会重新加载整个页面。它第一次工作 - 即第一次搜索,但是对于未来的搜索,展开折叠功能停止工作。我认为是因为页面没有重新加载,但我不知道如何修复它。

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2   /jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function () {
$('.section').hide();
 $('h2').click(function () {
    $(this).toggleClass("open");
    $(this).next().toggle();
}); //end toggle

}); //end ready

</script>

<?php include('db.php');
$descr = $_POST['search'];
 echo '<ul id="user_list">';
 $user_query = $db->query("SELECT * FROM tblVulns WHERE Name LIKE '%".$descr."%'");
 while($user = $db->fetch_assoc($user_query))
 {
      echo ' <h2 style="cursor:pointer">'.stripslashes($user['Name']).'</h2>
    <div class="section" style="display:none">  <h3>'.stripslashes($user['Risk']).'</h3><p>
    <h4>'.stripslashes($user['Summary']).'<p>'
    .stripslashes($user['Description']).'<p>'
    .stripslashes($user['cveCode']).'<p></div>';
 }
?>

底部的代码是接收搜索结果的php。最上面的代码是处理展开和折叠的js

在页面加载后如何为所有搜索进行这项工作的任何帮助都会很棒。谢谢

【问题讨论】:

  • 你应该如何在不重新加载页面的情况下接收未来的搜索结果?

标签: php javascript expand collapse


【解决方案1】:

您正在将事件侦听器添加到页面加载时出现的任何h2 元素的单击事件。听起来您正在加载新内容并期望相同的代码适用于它们。

相反,您需要这样做:

$("body").on("click","h2",function(){
     $(this).toggleClass("open");
     $(this).next().toggle();
});

这将适用于页面上的任何h2。如果您只希望某个容器中的 h2s 产生效果,请替换 body 以获得对该元素的引用

编辑:

我现在看到您使用的是不支持 on() 函数的相当旧版本的 jQuery。如果可以,我建议升级,如果不能,请使用 Abhishek Saha 的答案。

【讨论】:

    【解决方案2】:

    我认为其中一个原因,第一次搜索后它不起作用是因为加载的新元素没有与点击动作绑定。

    试试这个:

    替换

    $('h2').click(function () {
        $(this).toggleClass("open");
        $(this).next().toggle();
    });
    

    $('h2').live('click',function () {
        $(this).toggleClass("open");
        $(this).next().toggle();
    });
    

    【讨论】:

    • 来自 jQuery 文档:从 jQuery 1.7 开始,不推荐使用 .live() 方法。使用 .on() 附加事件处理程序。 旧版本 jQuery 的用户应优先使用 .delegate() 而非 .live()
    • 抱歉,我看到 delegate() 实际上并没有出现在 jQuery 1.3.2 中。
    • .on() 将是一个更好的选择......对不起,我知道 live() 方法已被弃用,但它只是让我忘记了。一个月没写代码了……
    猜你喜欢
    • 2015-02-15
    • 1970-01-01
    • 2012-05-30
    • 1970-01-01
    • 2012-05-15
    • 2014-02-26
    • 2012-01-14
    • 1970-01-01
    • 2015-09-05
    相关资源
    最近更新 更多