ajax 从动态填充的按钮列表中单击复选按钮

ajax check button is clicked from a dynamically populated list of buttons

您好,我是 ajax 的新手,我收到了来自 django 的 json 响应,其中包含要显示为按钮列表的名称列表。单击按钮后,我想将其禁用。

下面是我目前写的html代码,按钮显示成功但没有执行禁用按钮操作。

我还想请问这个onclick函数的范围是什么?函数是否在大括号 } 的末尾终止?或者这个函数是否检查它是否超出范围?

<h3>User List:</h3>
<ul id="userLists"> </ul>
$(document).ready(function(){
    $.ajax({
        type:"GET",
        // getUserList is a django views where it query the database and returns JsonResponse of the user's name
        url: "{% url 'getUserList' %}",
        success: function(response){
        $("#userLists").empty();
        // Create a list according to number of users in json
        for (var key in response.users){
            var temp="<button type=\"button\", name=\""+ response.users[key].user +"\", class=\"btn btn-outline-danger\">" + response.users[key].user + "</button>";
            $("#userLists").append(temp);


            // Here I want to do when clicked, it disables the button and leave others as is.
            // Current implementation does not work...

            document.getElementsByName(response.users[key].user).onclick =
            function(){document.getElementsByName(response.users[key].user).prop('disabled', true)};

            };
        }
    });
})

我也试过下面的实现方式,还是不行...

if(document.getElementsByName(response.user[key].user).clicked == true){
    document.getElementsByName(response.user[key].user).prop("disabled", true);
};

谢谢大家

getElementsByName returns一个节点列表...所以是匹配元素的集合。
这就是 .onclick.prop("disabled", true) 没有效果的原因。

如果response.users[key].user是唯一的,你可以安全地使用document.getElementsByName(response.user[key].user)[0]
所以添加 [0] 以定位第一个匹配项。

关于引用 messing-with,您可能有兴趣阅读有关 template literals.

的内容