如何将函数的返回值作为事件后显示在div元素中的文本添加到DOM中



所以我有一个返回字符串的函数。我希望在不同的div中按下按钮后,该字符串显示在div中

<div >
<button id="something"> something </button>
</div>
<div id="results">
want result to show up here
</div>
const something = document.querySelector('#something');
something.addEventListener('click', someFunction);
function someFunction(a, b){
......
// returns a string and takes two parameters, one parameter from the user 
}
const results = document.querySelector('#results');
// how to add return value of someFunction as text in the #results div?

据我所知,您需要打印someFunction返回的值,并将其显示在result元素中。

你可以像这样重组你的代码-

const something = document.querySelector('#something');
const results = document.querySelector('#results'); // your result div
// you missed the function keyword
function someFunction(a, b) {
......
// returns a string and takes two parameters, one parameter from the user 
}
something.addEventListener('click', () => {
const resultText = someFunction(a, b); // you need to give the value for a nad b
result.textContent = resultText;
});

此外,在您的方法中,您没有将任何参数传递给someFunction

最新更新