我正在查看此问题post,但在将其应用于我的代码时遇到了麻烦。
这让我感到困惑,因为我正在为保存按钮做完全一样的事情,因为我是取消按钮(至少是关闭它的那一部分),单击取消后什么也没有发生。
<dialog class="my-modal">
<p>Add Cust</p>
<label for="nameField">Name</label><input id=nameField><br>
<label for="addressField">Address</label><input id=addressField><br>
<label for="cityField">City</label><input id=cityField><br>
<label for="stateField">State</label><input id=stateField size=2>
<label for="zipField">Zip</label><input id=zipField><br>
<br>
<button onclick="closeAndSave()">Save</button>
<button onclick="close()">cancel</button>
</dialog>
function close(){
const modal = document.querySelector('.my-modal');
modal.close();
}
也尝试过:
<button class="btn btn-default" data-dismiss="my-modal" aria-label="Close">Cancel</button>
close()
在您的应用程序全局范围中的其他地方重新定义/重新分配,则将导致对话框的关闭按钮调用“错误的关闭功能”。考虑修改HTML和脚本,以便将事件绑定委托给脚本以进行更好的控制,如下所示:
/* Obtain modal as before */
const modal = document.querySelector('.my-modal')
/* Select buttons from modal and bind click behavior */
modal.querySelector("button.cancel").addEventListener("click", () => {
/* Call close method on modal to dismiss */
modal.close();
});
modal.querySelector("button.save").addEventListener("click", () => {
alert("save data");
modal.close();
});
/* Added for snippet to prelaunch dialog */
modal.showModal();
<dialog class="my-modal">
<p>Add Cust</p>
<label for="nameField">Name</label><input id=nameField><br>
<label for="addressField">Address</label><input id=addressField><br>
<label for="cityField">City</label><input id=cityField><br>
<label for="stateField">State</label><input id=stateField size=2>
<label for="zipField">Zip</label><input id=zipField><br>
<br>
<!-- Replace onclick with classes to identify/access each button -->
<button class="save">Save</button>
<button class="cancel">cancel</button>
</dialog>
希望有帮助!