首页 > 解决方案 > 用户提交后如何执行 HTML 代码

问题描述

我希望用户加载他们选择的 Movie.swf 大小。我有两个输入框,一个用于宽度,一个用于高度。如何以用户提交的大小执行对象?

我不知道如何使这项工作。

//Let the user set the size for Movie.swf
<label for="fname">Width</label><br>
<input type="text" id="objW"><br><br>
  
<label for="fname">Height</label><br>
<input type="text" id="objH"><br><br>

//Movie.swf will load with a new size from the input box
<input type="submit" value="Execute"><br>

//Execute this line when submit
<object width="" height="" data="/Movie.swf"></object>

标签: htmlinput

解决方案


除非您已经在使用框架,否则您需要为此部分添加 javascript 代码。此外,您应该将输入包装在form标签内并添加 on submit eventlistener

在当前情况下,以下代码应该可以工作:

const objW = document.getElementById('objW');
const objH = document.getElementById('objH');
const submitInput = document.querySelector('input[type=submit]');
const body = document.getElementsByTagName('body')[0];
submitInput.addEventListener('click', e => {
  e.preventDefault();

  /*if you want to display the object element after clicking input submit and replace all input fields*/
  body.innerHTML = `<object width="${objW.value}" height="${objH.value}" data="/Movie.swf"></object>`;

  /*or you can use following code if you always have object element in your html*/
  const object = document.getElementsByTagName('object')[0];
  object.setAttribute("height", objH.value);
  object.setAttribute("width", objW.value);

});

推荐阅读