Typeerror:仅限FireFox中的未定义表单元素

时间:2014-05-31 00:10:41

标签: javascript firefox

出于某种原因,我只在FireFox中收到错误:

  

Typeerror:document.forms.myCity.optionname未定义

该脚本适用于所有其他浏览器:

function WriteCookie()
{
    document.cookie = "city" + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
    cookievalue = document.forms['myCity'].optionname.value + ";";

    document.cookie='city='+cookievalue +'; expires=Fri, 3 Aug 2021 20:47:11 UTC; path=/';
    window.location.href = "http://mywebsite.com";

}

此脚本位于标题中,由此表单执行:

<form name="myCity" action="http://mywebsite.com/"  method="POST">

<?php

  function get_terms_dropdown($taxonomies, $args){

    $myterms = get_terms($taxonomies, $args);

    $optionname = "optionname";

    $emptyvalue = "";

    $output ="<select name='". $optionname ."'><option selected='". $selected . "' value='" . $emptyvalue . "'>Select a City</option>'";

    foreach($myterms as $term){

      $term_taxonomy=$term->pa_city; //CHANGE ME

      $term_slug=$term->slug;

      $term_name =$term->name;

      $link = $term_slug;

      $output .="<option name='".$link."' value='".$link."'>".$term_name."</option>";

    }

    $output .="</select>";

    return $output;

  }

  $taxonomies = array('pa_city'); 

  $args = array('order'=>'ASC','hide_empty'=>true);

  echo get_terms_dropdown($taxonomies, $args);

?>

<input type="submit" value="click" name="submit" onclick="WriteCookie()">

</form> 

错误只出在FireFox中,有什么想法吗?

1 个答案:

答案 0 :(得分:4)

您的错误是:

  

Typeerror:document.forms.myCity.optionname未定义

我认为问题出在这个元素中:

<form name="myCity" action="http://mywebsite.com/"  method="POST">

看起来表单使用id选择器而不是name选择器。之前我遇到过这个问题,我通过将idname放入<form>元素来解决它。我能找到的唯一明确的在线参考是here from the MSN XHTML Standards page

  

XHTML 1.1中不允许表单元素的name属性   准则。

我也是found a discussion thread here关于XHML 1.1严格标准&amp;也引用它的表格:

  

W3表示不推荐使用name属性作为HTML的弃用部分   4.0,只有ID标签符合新的XHTML 1.1标准。

然后我发现this official W3 reference指出问题在头上;重点是我的:

  

name = cdata [CI]   此属性为元素命名,以便它可以   从样式表或脚本中提到。 注意。这个属性有   为了向后兼容而被包括在内。应用程序应该使用   id属性用于标识元素。

所以只需向该元素添加id属性,如下所示:

<form name="myCity" id="myCity" action="http://mywebsite.com/"  method="POST">

您希望同时包含nameid,以涵盖不同浏览器的所有基础及其XHTML 1.1标准的实现。

但如果某种方法仍然不起作用,只需在id更改之上的JavaScript中执行此操作:

function WriteCookie()
{
    document.cookie = "city" + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
    cookievalue = document.getElementById("myCity").optionname.value + ";";

    document.cookie='city='+cookievalue +'; expires=Fri, 3 Aug 2021 20:47:11 UTC; path=/';
    window.location.href = "http://mywebsite.com";

}

我更改了这样的行:

cookievalue = document.forms['myCity'].optionname.value + ";";

要成为这样:

cookievalue = document.getElementById("myCity").optionname.value + ";";
相关问题