动态创建的按钮未出现

时间:2019-09-19 14:04:43

标签: javascript jquery

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

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

1 个答案:

答案 0 :(得分:-1)

您需要的是将新元素append放入某个容器。

{{3}}

这是我的示例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>