$("")[0].点击(); ajax 调用后不工作

$("")[0].click(); not working after ajax called

调用ajax后我会模拟点击下载文件生成link.

Jquery :

$(document).ready(function(){
    $(".vignette-dl").click(function() {
        var id = $(this).find("a").attr("value");
        $.ajax({
            type: "POST", 
            url: "testDL.php",
            data: { dossier: $("#selectDossier").val(), id_doc: id },
            success: function(result){
                $("#secretDiv").html(result);
            }
        });

        $(document).ajaxComplete(function(){
            alert("test");
            $("#forcedl")[0].click(function(){
                alert("test42");
            }); 
        });
    });
});

result var 在 secretDiv 中添加一个 html link with id="forcedl" 并完美运行。

ajax调用了完整函数,因为我看到了我的警报测试,但是点击模拟没有工作,我没有看到警报测试42。

我也不知道为什么..

jQuery.click(handler) 仅在单击元素时调用处理程序。

$(document).ready(function(){
    $(".vignette-dl").click(function() {
        var id = $(this).find("a").attr("value");
        $.ajax({
            type: "POST", 
            url: "testDL.php",
            data: { dossier: $("#selectDossier").val(), id_doc: id },
            success: function(result){
                $("#secretDiv").html(result);
                $("#forcedl").click();
            }
        });
    });
    $(document).on('click', '#forcedl', function(e) {
        e.preventDefault();
        window.location.href = $(this).attr('href'); // use href-attribute or just replace with your path/to/file
    })
});

要下载 PDF,您需要更改 Response-Header - 这必须在服务器端完成。 请参阅下面的 .htaccess 示例,它将直接下载所有以任何大小写结​​尾的 .pdf 文件。

<FilesMatch "\.(?i:pdf)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>

对于 php 示例,请检查下面的代码示例。

<?php
header('Content-type: application/pdf');
header('Content-disposition: attachment; filename=myNewFileName.pdf');
readfile("uri/to/my/file.pdf");

整个方法不合逻辑,你不能有以下 -

成功时 -> 点击时。

解决方法,创建一个变量设置为=0。

在 ajax 成功方法 make 变量 = 1.

if === 0 {
 // nothing here
}else{
  // must ===1 something here
}

比别人的想法快多了

根据您的描述,我相信这是您的愿望,但我做了一些假设。

$(document).ready(function() {
  $("#secretDiv").on('click', "#forcedl", function() {
    alert("test42");
  });
  $(".vignette-dl").click(function() {
    var id = $(this).find("a").attr("value");
    $.ajax({
      type: "POST",
      url: "testDL.php",
      data: {
        dossier: $("#selectDossier").val(),
        id_doc: id
      }
    }).done(function(result) {
      $("#secretDiv").html(result);
    }).complete(function() {
      alert("test");
      $("#forcedl").trigger('click');
    });
  });
});