首页 > 解决方案 > 动态创建的按钮没有出现

问题描述

我已经动态地创建了两个按钮,它们将在按钮单击时出现,但这些按钮没有出现,我认为从我所做的研究来看,这是由于在页面加载后试图添加按钮。然后我尝试使用 $('body').on('click', '.edit', edit); 按照此处的说明添加按钮。

$(document).ready(function() {
  $('body').on('click', '.edit', edit);

  function edit() {

    var edit = $(this);
    var value = edit.val();
    edit.hide();
    var cancelBtn = document.createElement('button');
    cancelBtn.type = "button";
    cancelBtn.name = "Cancel";
    cancelBtn.className = "btn btn-primary cancel";
    cancelBtn.style.visibility = 'visible';

    var saveBtn = document.createElement('button');
    saveBtn.type = "submit";
    saveBtn.value = value;
    saveBtn.name = "Save Changes";
    saveBtn.className = "btn btn-primary save";
    saveBtn.formAction = '@Url.Action("Edit")';
    saveBtn.style.visibility = 'visible';


    $(".cancel").click(function cancel() {
      edit.show();
      document.getElementById("save").style.visibility = "hidden";
      document.getElementById("cancel").style.visibility = "hidden";
    });
  };
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button type="button" class="edit">Edit</button>
<button type="button" class="cancel">Cancel</button>

标签: javascriptjquery

解决方案


您需要的是将append您的新元素添加到某个容器中。

https://www.w3schools.com/jquery/jquery_dom_add.asp

这是我的示例 js 代码:

$(document).on('click', '.edit', function() {
    debugger;
    //It's much easier to create element by html string with jQuery
    $('.actions').append('<button id="cancel" class="btn btn-primary cancel">Cancel</button>');
    $('.actions').append('<button id="save" type="commit" class="btn btn-primary save" value="' + $(this).val() + '">Save</button>');

    $(this).hide();

});
$(document).on('click', '.save', function() {
    alert('saved');
    $(this).remove();
    $('#cancel').remove();
})

$(document).on('click', '.cancel', function() {
    $(this).remove();
    $('#save').remove();
})

这是示例html:

<HTML>
<BODY>
    <form id="dosomething">
        <div class='actions'>
            <button type="button" class="edit" value="some value">Click Me!</button>
        </div>
    </form>
</BODY>
</HTML>

推荐阅读