我是编码的新手,我一直在尝试学习按钮和事件处理程序。 如果说有50个按钮,那将是一种管理列出的事件处理程序的更简单的方法,因此代码不会重复/被污染。
function addText(add) {
document.getElementById('words').value = add.value;
}
function takeText(take) {
document.getElementById('words').value = document.getElementById('words').value.replace(take.value, '');
}
<button value="example 1" onmouseover="addText(this)" onmouseout="takeText(this)">Button1</button>
<button value="example 2" onmouseover="addText(this)" onmouseout="takeText(this)">Button2</button>
<button value="example 3" onmouseover="addText(this)" onmouseout="takeText(this)">Button3</button>
<input type="text" id="words">
答案 0 :(得分:1)
.btnWord
添加到所有所需按钮中mouseenter
一起使用mouseleave
Element.addEventListener()
个事件来触发您的特定功能操作
const el_btnWord = document.querySelectorAll('.btnWord');
const el_words = document.querySelector('#words');
const fn_setWord = (ev) => el_words.value = ev.target.value;
const fn_clearWord = () => el_words.value = '';
el_btnWord.forEach(el => {
el.addEventListener('mouseenter', fn_setWord);
el.addEventListener('mouseleave', fn_clearWord);
});
<button class="btnWord" value="example 1">Button1</button>
<button class="btnWord" value="example 2">Button2</button>
<button class="btnWord" value="example 3">Button3</button>
<input type="text" id="words">
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
https://developer.mozilla.org/en-US/docs/Web/API/Event/target
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelectorAll
UI考虑因素
由于个人而言,在mouseenter上更改输入value
毫无意义-而不是在mouseleave上删除输入,我建议(如果是所需的UX)使用placeholder
,并更改仅在点击上显示值:
const el_btnWord = document.querySelectorAll('.btnWord');
const el_words = document.querySelector('#words');
const fn_setPH = (ev) => el_words.placeholder = ev.target.value;
const fn_clearPH = () => el_words.placeholder = '';
const fn_setVAL = (ev) => el_words.value = ev.target.value;
el_btnWord.forEach(el => {
el.addEventListener('mouseenter', fn_setPH);
el.addEventListener('mouseleave', fn_clearPH);
el.addEventListener('click', fn_setVAL);
});
<button class="btnWord" value="example 1">Button1</button>
<button class="btnWord" value="example 2">Button2</button>
<button class="btnWord" value="example 3">Button3</button>
<input type="text" id="words">
答案 1 :(得分:0)
您可以使用JavaScript querySelector和add events对元素进行操作。
将事件添加到javascript代码的元素上也被认为是一种更好的做法。
let buttons = document.querySelectorAll('button');
buttons.forEach(button => {
button.addEventListener('onmouseover', addText);
button.addEventListener('takeText', takeText);
});