单击仅在第二次单击后有效

Onclick works only after second click

本文关键字:单击 有效 第二次      更新时间:2023-09-26

我有一个HTML列表,看起来像

<a onclick="open_file()" id="3.txt">3.txt</a>

我的open_file()函数正在查找此

function open_file() {
    $("a").click(function (event) {
        var file_name = event.target.id;
        $("#f_name").val(file_name);
        $.ajax({
            url: "docs/" + file_name,
            dataType: "text",
            success: function (data) {
                $("#text_form").val(data);
                $('#text_form').removeAttr('readonly');
                $('#delete_button').removeAttr('disabled');
                $('#save_button').removeAttr('disabled');
            }
        })
    });
}

问题是,只有在两次点击这样的链接后,函数才能最终将数据加载到所有字段(text_formf_name)中。即使我先点击一个文件,然后点击另一个文件并加载,它也能工作。有什么办法解决这个问题吗?

您目前正在做的是将一个onclick事件添加到一个链接中,该链接调用一个函数,该函数通过jQuery添加另一个onclik事件。

删除onclick属性和open_file()函数包装器,以便jQuery根据需要添加事件。

您不需要onclick="open_file()" this:

<div id='linkstofiles'>
    <a id="3.txt">3.txt</a>
    //other links go here
</div>
$("#linkstofiles a").click(function (event) {
    var file_name = event.target.id;
    $("#f_name").val(file_name);
    $.ajax({
        url: "docs/" + file_name,
        dataType: "text",
        success: function (data) {
            $("#text_form").val(data);
            $('#text_form').removeAttr('readonly');
            $('#delete_button').removeAttr('disabled');
            $('#save_button').removeAttr('disabled');
        }
    })
});

当html中有onclick时,您不需要在函数中再次绑定点击事件。

同样对于$ is not defined,您需要将jquery库放在头部。