带文本框的iframe

时间:2018-07-24 20:44:30

标签: javascript html iframe

我的代码有什么问题?只有第二个iframe起作用,而第一个方框则无效。

任何帮助将不胜感激。

<form action="" method="post" id="url-setter">
  <input type="text" value='' name="url" id="url" />
  <button type="submit" name="submit">Submit</button>
</form>
<iframe id="the-frame" width="540" height="480"></iframe>
<iframe id="the-frame1" width="540" height="480"></iframe>
<script type="text/javascript">
  (function() {
    "use strict";
    var url_setter = document.getElementById('url-setter'),
      url = document.getElementById('url'),
      the_iframe = document.getElementById('the-frame');
    url_setter.onsubmit = function(event) {
      event.preventDefault();
      the_iframe.src = url.value;
    };
  }());
  (function() {
    "use strict";
    var url_setter = document.getElementById('url-setter'),
      url = document.getElementById('url'),
      the_iframe = document.getElementById('the-frame1');
    url_setter.onsubmit = function(event) {
      event.preventDefault();
      the_iframe.src = url.value;
    };
  }());
</script>

1 个答案:

答案 0 :(得分:0)

首先,不要分配onsubmit两次,其次,当url触发时,您需要获取onsubmit元素值,否则将没有任何值。 / p>

堆栈片段

<form action="" method="post" id="url-setter">
  <input type="text" value='' name="url" id="url" />
  <button type="submit" name="submit">Submit</button>
</form>
<iframe id="the-frame" width="540" height="480"></iframe>
<iframe id="the-frame1" width="540" height="480"></iframe>
<script type="text/javascript">
  (function() {
    "use strict";
    var url_setter = document.getElementById('url-setter'),
      the_iframe = document.getElementById('the-frame'),
      the_iframe1 = document.getElementById('the-frame1');

    url_setter.onsubmit = function(event) {
      event.preventDefault();
      var url = document.getElementById('url');
      the_iframe.src = url.value;
      the_iframe1.src = url.value;
    };
  }());
</script>