简体   繁体   English

向元素添加数据属性在第一次尝试时不起作用

[英]Adding data attribute to element doesn't work on first try

I have an edit button inside td that when clicked opens a modal.我在 td 中有一个编辑按钮,单击该按钮会打开一个模态。 The form in the modal body loads from an external file.模态主体中的表单从外部文件加载。 I'd like to pass the row id value to the form.我想将行 id 值传递给表单。 In my attempt, the id isn't passed on the very first click(it returns undefined) but on the subsequent ones it works perfectly fine.在我的尝试中,id 没有在第一次点击时传递(它返回未定义),但在随后的点击中它工作得很好。

Here's the html code:这是html代码:

 <button type="button" class="btn" id="edit" 
data-id="<?php echo $row['id'] ;?>"></button>

Script:脚本:

  $(document).ready(function() {
        $("#tableCountries tbody tr td button.btn").on("click", function() {
            if ($(this).attr("id") == "edit") {
                //fetch row id from button
                var rowid = $(this).data('id');
                //open modal
                var modal = $("#modalCountries").modal();
                //load external form into modal body
                modal.find('.modal-body').load("modal.html #countries_form");
                //add row id value to countries form
                $("#countries_form").attr('data-value', rowid);
                //check value of id
                var newid = $("#countries_form").data('value');
                alert(newid);
             }
        });
    });

I've tried using bind() or live() instead of on(), I've tried using data() instead of attr() to assign id, I've also tried putting load() outside the if statement.我试过使用 bind() 或 live() 而不是 on(),我试过使用 data() 而不是 attr() 来分配 id,我也试过将 load() 放在 if 语句之外。 None of it works.它都不起作用。 Any help would be appreciated.任何帮助,将不胜感激。

.load() is asynchronous so you'll have to use its callback to run code after it finishes. .load()是异步的,所以你必须在它完成后使用它的回调来运行代码。

modal.find('.modal-body').load("modal.html #countries_form", function(){
    $("#countries_form").attr('data-value', rowid);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM