gpt4 book ai didi

javascript - 如何在表格中创建对话框

转载 作者:行者123 更新时间:2023-12-02 22:14:25 25 4
gpt4 key购买 nike

我不懂javascript,但我必须做作业。请帮助我向 HTML 表格添加一个对话框!我找到了一些 JavaScript 示例模式,但我不知道如何使它们与 HTMLtables 一起使用。

这就是我的 HTML 代码的样子,例如:

<!DOCTYPE html>
<html>

<head>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.1.1/material.indigo-pink.min.css">
<script defer src="https://code.getmdl.io/1.1.1/material.min.js"></script>
</head>

<body>
<table id="table">
<tr>
<td>
<button id="show-dialog" type="button" class="mdl-button">Show Confirmation Box</button>
<dialog class="mdl-dialog">
<h4 class="mdl-dialog__title">Confirm</h4>
<div class="mdl-dialog__content">
<p> blah blah blah </p>
</div>
<div class="mdl-dialog__actions">
<button type="button" class="mdl-button">Confirm</button>
<button type="button" class="mdl-button close">Cancel</button>
</div>
</dialog>
</td>
</tr>
<tr>
<td>
<button id="show-dialog" type="button" class="mdl-button">Show Confirmation Box</button>
<dialog class="mdl-dialog">
<h4 class="mdl-dialog__title">Confirm</h4>
<div class="mdl-dialog__content">
<p> blah blah blah </p>
</div>
<div class="mdl-dialog__actions">
<button type="button" class="mdl-button">Confirm</button>
<button type="button" class="mdl-button close">Cancel</button>
</div>
</dialog>
</td>
</tr>
</table>
</body>
</html>

这就是我发现的关于对话框的内容。我有一个想法,制作 querySelectorAll,然后在循环中执行所有操作,但它无法正常工作。我正在祈祷帮助!

<script>
var dialog = document.querySelector('dialog');
var showDialogButton = document.querySelector('#show-dialog');
if (! dialog.showModal) {
dialogPolyfill.registerDialog(dialog);
}
showDialogButton.addEventListener('click', function() {
dialog.showModal();
});
dialog.querySelector('.close').addEventListener('click', function() {
dialog.close();
});
</script>

最佳答案

你的问题一定是因为这里的选择器。 id 选择器在整个 html 中必须是唯一的。如果您想访问多个项目,则必须使用 class 属性(或自定义 data-* 属性)。因此,为按钮添加一个类属性。将您的代码更改为,

html

...
<button id="show-dialog-btn1" type="button" class="mdl-button show-dialog">Show Confirmation Box</button>
...
<button id="show-dialog-btn2" type="button" class="mdl-button show-dialog">Show Confirmation Box</button>
...
<script>
var dialog = document.querySelector('dialog');
var showDialogButtons = document.querySelectorAll('.show-dialog');
if (! dialog.showModal) {
dialogPolyfill.registerDialog(dialog);
}
for (let i = 0; i< showDialogButtons.length;i++){
showDialogButtons[i].addEventListener('click', function() {
dialog.showModal();
});
}
dialog.querySelector('.close').addEventListener('click', function() {
dialog.close();
});
</script>

并确保为每个按钮分配不同的 id 值。

关于javascript - 如何在表格中创建对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59439396/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com