简体   繁体   English

如何在HTML中输出带有onclick参数的函数值?

[英]How to output a value of a function with parameters onclick in HTML?

I have a function that outputs a random number and I want to output the value below the button when it's clicked.我有一个输出随机数的函数,我想在单击按钮时输出按钮下方的值。

<!DOCTYPE html>
<html>
<body>

<form>
  <input type="button" value="Click me" onclick="genRand()">
</form>

<script type="text/javascript">
function genRand(min, max, decimalPlaces) {  
  var rand = Math.random()*(max-min) + min;
  var power = Math.pow(10, decimalPlaces);
  return Math.floor(rand*power) / power;
}
</script>

</body>
</html>

If I want the rest of the page to stay when the button is clicked I believe I need to use innerhtml, but I'm having no luck working out how to incorporate it into the code.如果我希望在单击按钮时保留页面的其余部分,我相信我需要使用 innerhtml,但是我没有找到如何将其合并到代码中的运气。

I'm new to html and javascript, so any help is really appreciated.我是 html 和 javascript 的新手,所以非常感谢任何帮助。

Something like this:像这样的东西:

 function genRand(min, max, decimalPlaces) { var rand = Math.random()*(max-min) + min; var power = Math.pow(10, decimalPlaces); var result = Math.floor(rand*power) / power; document.getElementById("result").innerHTML = result; }
 <input type="button" value="Click me" onclick="genRand(0,10,2)"> <div id="result"></div>

You need to pass values when you are calling the function.调用函数时需要传递值。

<input type="button" value="Click me" onclick="genRand('Minimum Value', 'Maximum Value','Decimal Places')">

For Eg:例如:

<input type="button" value="Click me" onclick="genRand(1,10,2)">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM