提问人:Sealington 提问时间:11/13/2023 最后编辑:Rory McCrossanSealington 更新时间:11/13/2023 访问量:34
如何使两个按钮打开不同的对话框
How do i make two buttons open a different dialog box
问:
我希望它像这样工作:
+-----------+ +--------------------+
| button1 |------------------->| I am a dialog box. |
+-----------+ +--------------------+
+-----------+ +-------------+
| button2 |--------------------------------------->| Hello World |
+-----------+ +-------------+
但结果是这样的:
+-----------+ +--------------------+
| button1 |------------------->| I am a dialog box. |
+-----------+ +--------------------+
+-----------+
| button2 |
+-----------+
<button class="o">How To Make MadLibs in JS</button>
document.addEventListener('DOMContentLoaded', function() {
var dialog = document.querySelector('dialog');
if (document.querySelector('.o')) {
document.querySelector('.o').onclick = function() {
dialog.show();
};
}
if (document.querySelector('.c')) {
document.querySelector('.c').onclick = function() {
dialog.close();
};
}
if (document.querySelector('.p')) {
document.querySelector('.p').onclick = function() {
print();
dialog.close();
};
}
});
如果你需要更多代码来修复它,它在这里:https://lesscodegreater--seamore.repl.co/
我尝试使用 ai 生成一个,尝试使用堆栈溢出答案,没有一个有效,没有一个有意义,我现在求助于询问。
另外,我正在使用对话框 TAG,而不是其他东西,我正在使用 .<dialog>
答:
0赞
captainbread
11/13/2023
#1
- 您必须以某种方式区分两个按钮和两个对话框。给他们一个领域就可以了。
id
<button class="o" id="dna-btn">How to make DNA ... </button>
<button class="o" id="madlibs-btn">How to make MadLibs ... </button>
- 之后,您必须区分两个对话框。也在此处使用该属性
id
<dialog id="dna-dialog"> ... </dialog>
<dialog id="madlibs-dialog"> ... </dialog>
- 修改 js 以使用新创建的 id
document.addEventListener('DOMContentLoaded', function() {
const dnaDialog = document.querySelector('#dna-dialog');
if (document.querySelector('#dna-btn')) {
document.querySelector('#dna-btn').onclick = function() {
dnaDialog.show();
};
}
if (document.querySelector('.c')) {
document.querySelector('.c').onclick = function() {
dnaDialog.close();
};
}
if (document.querySelector('.p')) {
document.querySelector('.p').onclick = function() {
print();
dnaDialog.close();
};
}
const madlibsDialog = document.querySelector('#madlibs-dialog');
if (document.querySelector('#madlibs-btn')) {
document.querySelector('#madlibs-btn').onclick = function() {
madlibsDialog.show();
};
}
});
自选
此外,如果您在按钮上使用属性,它将减少 javascript 代码。onclick
<button class="o" onclick="dna.show()" >How to make DNA ... </button>
<button class="o" onclick="madlibs.show()">How to make MadLibs ... </button>
...
<dialog id="dna-dialog"> ... </dialog>
<dialog id="madlibs-dialog"> ... </dialog>
const dna = document.getElementById('dna-dialog');
const madlibs = document.getElementById('madlibs-dialog');
评论