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

我在 td 中有一个编辑按钮,单击该按钮会打开一个模式。模态主体中的表单从外部文件加载。我想将行 id 值传递给表单。在我的尝试中,id 不会在第一次点击时传递(它返回未定义),但在后续点击中它工作得很好。


这是 HTML 代码:


 <button type="button" class="btn" id="edit" 

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

脚本:


  $(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);

             }

        });

    });

我尝试过使用bind()或live()而不是on(),我尝试过使用data()而不是attr()来分配id,我也尝试过将load()放在if语句之外。这些都不起作用。任何帮助,将不胜感激。


浮云间
浏览 97回答 1
1回答

慕尼黑的夜晚无繁华

.load()是异步的,因此您必须在完成后使用其回调来运行代码。modal.find('.modal-body').load("modal.html&nbsp;#countries_form",&nbsp;function(){ &nbsp;&nbsp;&nbsp;&nbsp;$("#countries_form").attr('data-value',&nbsp;rowid); });
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript