javascript - 动态创建的按钮没有出现
问题描述
我已经动态地创建了两个按钮,它们将在按钮单击时出现,但这些按钮没有出现,我认为从我所做的研究来看,这是由于在页面加载后试图添加按钮。然后我尝试使用 $('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>
解决方案
您需要的是将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>
推荐阅读
- flutter - 使用 BLOC (flutter) 监听 firestore 集合变化的最小代码
- python - Pandas:查找每个间隔中最大连续零计数的平均值
- javascript - 为什么即使最大宽度设置为 100%,我的 (json) 图像也会超出边界/容器?
- angular - Angular Reactive Form - 验证不起作用
- mysql - 如何在MySql中同时编写删除和更新查询的过程
- spring-boot - 有没有办法打印对象的值?
- html - 在 django 模板中显示 excel 文件
- jdbc - 我们可以使用 JDBC 连接器在 Power BI 中获取数据吗
- excel - Excel 2010 电子邮件 VBA 发送整个工作簿
- ios - 如何在加载 CollectionView 2-3 秒后仅显示 collectionView 的选定单元格