嵌套函数(JavaScript)

时间:2018-12-15 19:02:15

标签: javascript html

<form name="f1" method="GET">

    <form name="f1">
<input type="text" name="rd" id="rd">
<input type="text" name="fala" id="rd">
<button onclick="cal()"></button>





    </form>

如何在javascript中使用嵌套函数来以HTML打印一些输出。

function abc() {
  var radius = document.f1.rd.value;
  document.write(radius)
}

function def() {
  var fala = document.f1.fala.value;
  document.write(fala)
}

function cal() {
  def()
  abc()
}

嵌套函数应由单个函数调用,然后将在单击事件中的按钮中使用

3 个答案:

答案 0 :(得分:2)

// Cache the elements and add a click listener to the button
const out = document.getElementById('out');
const button = document.querySelector('button');
button.addEventListener('click', cal, false);

function abc() {
  var radius = document.f1.rd.value;

  // Instead of using `document.write`
  // append the value to the output div
  out.innerHTML += radius + '<br />';
}

function def() {
  var fala = document.f1.fala.value;
  out.innerHTML += fala + '<br />'
}

function cal(e) {

  // Prevent the form from submitting to the server
  e.preventDefault();
  def();
  abc();
}
<form name="f1">
  <label>RD</label><input name="rd" />
  <label>FALA</label><input name="fala" />
  <button>Cal!</button>
</form>
<div id="out"></div>

答案 1 :(得分:2)

两件事:

    默认情况下,button中的
  • form会发起submit,您可以通过将其type设置为button
  • 来“中和”它们。
  • document.write()破坏了页面,使用元素来发出结果(例如div)及其innerHTML

function cal(){
  result.innerHTML=rd.value+", "+fala.value;
}
<form name="f1" method="GET">
  <input type="text" name="rd" id="rd"><br>
  <input type="text" name="fala" id="fala"><br>
  <button type="button" onclick="cal()">Click me!</button>
</form>
<div id="result"></div>

答案 2 :(得分:0)

尝试使用控制台日志并阻止默认表单提交。

<form name="f1">
    <input type="text" name="rd" id="rd0">
    <input type="text" name="fala" id="rd1">
    <button onclick="cal(event)">click</button>
</form>

<script type="text/javascript">
function abc() {
  var radius = document.forms.f1.rd.value;
  console.log(radius);
}

function def() {
  var fala = document.forms.f1.fala.value;
  console.log(fala);
}

function cal(event) {
  def();
  abc();
  event.preventDefault();
}
</script>