【问题标题】:How to replace document.write with something more appropriate如何用更合适的东西替换 document.write
【发布时间】:2012-09-12 21:35:18
【问题描述】:

我有一些旧代码,其中包含 document.write。

<script type="text/javascript" language="JavaScript1.2">
document.write('<form name="InvGenPayDonation" action="'+PostURL+'" onsubmit="return validateForm();" method="POST">');
</script>

如何用加载页面时确定的 javascript 变量替换 action?这是该代码,它不是函数的一部分。 (我已经替换了名称,所以 substr 索引不正确,但我相信你明白了。)

// Check where we came from so that we can go to the right spot when the
// form gets posted from outside of our HTML tree.
var PostURL = '/event.php';

if (window.location.href.substr(0, 21) == 'http://10.10.10.10:80')
  PostURL = 'http://10.10.10.10:8580/event.php';
else if (window.location.href.substr(0, 14) == 'http://webapps')
  PostURL = 'http://10.100.0.11:8580/event.php';
else if (window.location.href.substr(0, 7) == 'webapps')
  PostURL = 'http://10.10.10.10:8580/event.php';
else if (window.location.href.substr(0, 10) == 'http://www')
  PostURL = 'https://secure.french.toast.new_zeland.france/event.php';

我希望 PostURL 进入表单的操作。如果我可以在没有 document.write 的情况下做到这一点,那就太好了。我只是需要一些帮助。谢谢。

【问题讨论】:

标签: javascript


【解决方案1】:

其他一些 DOM0 代码应该可以解决问题:

// Your code from the question here
document.forms[0].action = PostURL;

请注意,这假定您的表单是页面上的第一个表单 - 如果不是,请将 [0] 替换为表单的从零开始的索引。

但是,您可以(并且可能应该)使用不依赖于页面布局的更现代的解决方案。最简单的是document.getElementById - 只需在表单中添加一个 ID 属性(确保 ID 的值在整个页面中是唯一的),然后执行以下操作:

document.getElementById("yourFormID").action = PostURL;

【讨论】:

    【解决方案2】:

    好吧,你可以在 html 中创建你的表单,给它和 id,然后像这样:

    document.getElementById('myform').setAttribute('action', post_url);
    

    【讨论】:

      【解决方案3】:

      我会用 jquery 来做。如果您还不知道,您还需要包含 jquery 文件。

      $(document).ready(function() {
      var PostURL = '/event.php';
      
      if (window.location.href.substr(0, 21) == 'http://10.10.10.10:80')
        PostURL = 'http://10.10.10.10:8580/event.php';
      else if (window.location.href.substr(0, 14) == 'http://webapps')
        PostURL = 'http://10.100.0.11:8580/event.php';
      else if (window.location.href.substr(0, 7) == 'webapps')
        PostURL = 'http://10.10.10.10:8580/event.php';
      else if (window.location.href.substr(0, 10) == 'http://www')
        PostURL = 'https://secure.french.toast.new_zeland.france/event.php';
      
      
        $("#search-form").attr("action", PostURL);
      });
      
      <form action='' id="search-form">
      </form>
      

      【讨论】:

      • 你不需要 jQuery。
      • 你不必这样做,但如果他试图更新旧的 js,升级到 jQuery 系统可能会有好处,因为许多新插件让生活变得更加轻松。
      【解决方案4】:

      您可以根据自己的目的使用 jQuery。此代码将在没有 document.write 的情况下设置表单的操作:

      $("form[name=InvGenPayDonation]").attr("action", PostURL);
      

      【讨论】:

      • 你没有使用 jQuery。
      • 好的。确实,jQuery 是其中一种方法,但我想到的就是这些。
      猜你喜欢
      • 1970-01-01
      • 2017-01-29
      • 1970-01-01
      • 2014-02-09
      • 2021-09-16
      • 1970-01-01
      • 1970-01-01
      • 2016-07-03
      • 1970-01-01
      相关资源
      最近更新 更多