好的,所以我有以下问题:
我是否应该将事件侦听器直接添加到parent element
(模式弹出框(,其中此元素具有3 buttons
(2 用于关闭选项卡,1 用于提交数据(。
在listener function
分配一些类似的class methods
并操作整个功能(提交数据和显示 UI(:
document.getElementById('weather-modal-container').addEventListener('click', modal);
function modal(e) {
ui.closeModal(e);
weather.submitData();
e.stopPropagation();
}
或者我应该在父元素中添加 2 个click listeners
,一个用于关闭模式,一个用于提交数据。
document.getElementById('weather-modal-container').addEventListener('click', closeModal);
document.getElementById('weather-modal-container').addEventListener('click', submitData);
或者,一个侦听器直接连接到parent element
以操作UI
,另一个侦听器用于容器内的按钮。
document.getElementById('weather-modal-container').addEventListener('click', closeModal);
document.getElementById('button-inside-container').addEventListener('click', submitData);
好的,那么只有 1 个事件侦听器呢?
const MyDialog = document.querySelector('#weather-modal-container')
MyDialog.onclick=e=>{
let role = e.target.dataset.role
if (role)
{
e.preventDefault()
console.clear()
console.log (role)
switch (role){
case 'submitData':
console.log ('something is :', MyDialog.something.value)
// stuff about submiting data
break;
case 'closeModal':
// stuff about close modal
break;
}
}
}
#weather-modal-container { display: block; width: 30em; padding: 1em; border: 1px solid grey;}
a[data-role] { color: red; float: right;}
#weather-modal-container button { float: right; margin: 0 .3em 0 0 }
<form id="weather-modal-container">
<a href="#" title="closeModal" data-role="closeModal">X</a>
<p>Bla bla bla bla</p>
<input type="text" placeholder="with something" name="something" value="hello">
<a href="https://en.wikipedia.org" title="wikipedia" > wikipedia</a>
<br>
<button data-role="submitData">Send</button>
<button data-role="closeModal">Cancel</button>
</form>