Ajax:Ajax响应中的链接不起作用

Ajax: link in ajax response is not working

本文关键字:Ajax 链接 不起作用 响应      更新时间:2023-09-26

我已经尝试了所有可能的解决方案,但仍然不适合我。

我使用ajax调用一个php页面,比如livesearch.php,从索引页面获取实时搜索结果。

<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
        <script>
            $("#livesearch").on("click", "a.alert", function() {
                alert("here");
            });
        </script>   
        <script>
            function showResult(str) {
                if (str.length == 0) {
                    $("#livesearch").empty();
                    $("#livesearch").css('display', 'none');
                    return;
                }
                $.ajax({
                    type: "GET",
                    url: "livesearch.php?q=" + str,
                    success: function(responseText) {
                        $("#livesearch").html(responseText);
                        $("#livesearch").css('display', 'block');
                        $("#livesearch").css('background', '#fff');
                    }
                });
            }
        </script>
    </head>
    <body>
        <form>
            <input type="text" size="30" onkeyup="showResult(this.value)" onblur="showResult('')" placeholder="search here">
            <div id="livesearch" style="height:500px;width:900px;overflow-y:scroll;display:none;z-index:99999;"></div>
        </form>
        <div id="gentext" style="position:fixed;top:40px;z-index:-1;">This is just a dummy text to check if result div overshadow this line or not.</div>
    </body>
</html>

它工作良好,并列出了可能的搜索。现在,从搜索结果中,用户可以点击页面进行浏览,这很简单。只要点击链接,我就想抓住它并进行一些处理。参见以上代码中的以下部分:

$("#livesearch").on("click", "a.alert", function() {
    alert("here");
});

首先,我正在测试,如果我能够捕获ajax搜索返回的这个链接上的点击,那么请注意("此处"),但它不起作用。

请关闭

在添加链接后定义点击方法:

success: function(responseText)
{
   $("#livesearch").html(responseText);
   $("#livesearch").css('display', 'block');
   $("#livesearch").css('background', '#fff');
   $("#livesearch").on("click", "a.alert", function() 
   {
      alert("here");
   });
}

试试这个,让我们知道控制台返回了什么:

$.ajax({
    type: "GET",
    url: "livesearch.php?q=" + str,
    success: function(responseText) {
       console.log(responseText); //CHECK YOUR CONSOLE 
       $("#livesearch").append(responseText);
       $("#livesearch").css('display', 'block');
       $("#livesearch").css('background', '#fff');
       $("#livesearch").find(".alert").click(function(e) {
           e.preventDefault();
           alert("here");
       });
    }
});

实现这一点的另一种方法是构建像<a href="" onclick="return myFunction()"></a>这样的锚标记,然后创建JS函数:

myFunction(){
    alert("here")
    return false;
}