是否可以将这些函数合并为一个函数?



我试图让这个程序在按下指定的字符按钮时添加一个特殊字符。问题是,我将会有很多函数。我能不能只用一个函数,让所有按钮都能用?

//These are buttons
var aa = document.querySelector('#aa')
var oo = document.querySelector('#oo')
var uu = document.querySelector('#uu')
var khii = document.querySelector('#khii')
//This is the text box
var textBox = document.querySelector('#typeIn')

//Functions to add a character into the text box
function addAa() {
textBox.innerHTML += "ā";
}
function addOo() {
textBox.innerHTML += "ō";
}
function addUu() {
textBox.innerHTML += "ū";
}
function addKhii() {
textBox.innerHTML += "χ";
}
//Telling the buttons to call on the functions when clicked
aa.onclick = addAa
oo.onclick = addOo 
uu.onclick = addUu
khii.onclick = addKhii

另外:为什么这不起作用?

var aa = document.querySelector('#aa')
var textBox = document.querySelector('#text')
function addLetter(a) {
textBox.innerHTML += a
}
aa.onclick = addLetter("ā")

这只将字符添加到文本框中一次。然后点击按钮什么也不做。为什么会这样呢?

是的,你可以只用一个函数来做。将字符作为参数传递给函数。像这样:

版本与addEventListener(首选)

const btns = document.querySelectorAll('button');
const textBox = document.querySelector('#typeIn');
btns.forEach(b => {
b.addEventListener('click', e => {
textBox.innerHTML += e.target.getAttribute('data-char')
})
});
#typeIn {
margin:10px;
padding: 10px;
color: white;
min-height:40px;
background: gray;
}
<button data-char="aa">aa</button>
<button data-char="X">X</button>
<button data-char="ō">ō</button>
<button data-char="ū">ū</button>
<div id="typeIn"></div>

通常尽量避免onclick事件,而使用eventListener。

Version onclick Event

const textBox = document.querySelector('#typeIn');
function add(what) {
textBox.innerHTML += what;
}
#typeIn {
margin:10px;
padding: 10px;
color: white;
min-height:40px;
background: gray;
}
<button onclick="add('aa')">aa</button>
<button onclick="add('X')">X</button>
<button onclick="add('ō')">ō</button>
<button onclick="add('ū')">ū</button>
<div id="typeIn"></div>

你可以这样做:

  1. 为每个按钮添加(例如)数据值属性
<button data-value="A">A</button>
<button data-value="B">B</button>
<button data-value="C">C</button>
  1. 抓取所有按钮,并添加"click"事件监听器,如下所示:
document
.querySelectorAll('button') // Use appropriate class name here
.forEach(button =>
button
.addEventListener("click", (e) => 
console.log(e.target.dataset.value) // Do whatever you want here
)
)
  1. 根据需要修改listener函数体

这是我为演示创建的JsFiddle的链接。

最新更新