php - 动态加载 div 上的 Jquery

标签 php jquery ajax

我有以下代码,

html 表单

<form id="t-files">
    <a style="margin-left:160px;" class="list-directories" href="#">Select File Path</a><br><br>
    <div id="fileList"></div>
</form><br> 

获取文件夹名称的 Ajax 代码

 $('.folderLink').on('click', function (e) { 
    alert('hello');
    e.preventDefault();
    $.ajax({
        type: 'post',
        url: 'list-directories-inner.php',
        dataType: 'text',
        data: $('#t-files').serialize(),
        success: function (data) { 
            alert(data);
            //$("#fileList").html(data);
        }
    });
});  

处理文件夹名称的 php 文件

<?php        
    $path    = 'templates';
    $files = scandir($path);

    foreach($files as $result) {
         if ($result != "." && $result != ".." && $result != "desktop.ini")
            {
                  echo '<img src="img/folder.png" width="40px"><a name="'.$result.'" class = "folderLink" href="#">'.$result.'</a></img><br>';
            }

    }
?>

上面的代码使用ajax将模板内的所有文件夹名称显示为链接。这工作正常。现在我想转到显示的每个文件夹的子文件夹。当我单击链接时,它们都不起作用(没有警报)。忘记 ajax。这是我的 jQuery,它不起作用。

$('.folderLink').on('click', function (e) { 
    alert('hello');
}); 

整个事情发生在另一个 jquery 加载的 div 中。我无法弄清楚这个问题。请帮忙

最佳答案

您必须使用委托(delegate)事件绑定(bind)。仅当 .folderLink 已在 DOM 中时,直接事件绑定(bind)才有效。但在你的情况下它是动态生成的

$(document).on("click",".folderLink",function(){
 //do stuff
})

关于php - 动态加载 div 上的 Jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34965212/

相关文章:

php - Laravel 广播 : Notification vs Event

javascript - 将 Chartjs 的 php sql 值检索到 jquery/ajax 中

悬停时的 jQuery 随机链接颜色

javascript - 我的函数返回空。为什么?

javascript - 通过 PHP 返回 JavaScript - 好主意还是坏主意?

javascript - 如何让我的查询读取字母(Ñ)

php - 从 php 运行长 SAS 存储过程而无需挂起浏览器

php - 将复选框值发布到 php 文件

python - 这是在 Python/GAE 中返回 JSON 以在 JavaScript 中解析的正确方法吗?

asp.net - Dropdownlist Autopost 退回问题 : Remembering the selection