【问题标题】:Type error: x is undefined类型错误:x 未定义
【发布时间】:2012-09-12 17:32:30
【问题描述】:

我有这个标记

<form name="sortbyformtop">
   <select onchange="location.href=sortbyformtop.sortbyselecttop.options[selectedIndex].value" id="sortbyselecttop">
      <option value="/Search"></option>
      <option value="/Search?sortby=accommodationtype">Accommodation type</option>
      ...
   </select>
</form>

每当我在下拉列表中选择一个选项时,我都会在 Firebug 中收到这个 Javascript 错误:

TypeError: sortbyformtop.sortbyselecttop is undefined

这种事情在某种程度上是可能的吗?

【问题讨论】:

  • sortbyformtop的值是多少?
  • 我们可能需要更多代码,这里真的是未定义...
  • 如果你使用像 jQuery 这样的库来为你处理所有的 DOM 混乱,你会让你的生活变得更轻松(除非你真的对它的所有怪癖和烦恼)。如果您担心使用库的任何缺点,请阅读this post

标签: javascript html


【解决方案1】:

试试

location.href= document.getElementById('sortbyselecttop').options[document.getElementById('sortbyselecttop').selectedIndex].value;

或很快

location.href= this.options[this.selectedIndex].value;

因为this 在这种情况下等同于document.getElementById('sortbyselecttop');


selectedIndex 需要绑定到特定的 select 元素(它是 select 本身的属性),否则您正在寻找一个名为 selectedIndex 的全局(未定义)变量

【讨论】:

  • 我得到 TypeError: document.getElementById("sortbyselecttop")
  • 页面中有多少个具有该 ID 的元素?如果您只有一个sortbyselecttop,则代码应该可以正常工作。或者试试我的更新
  • 好吧,如果您使用 this 版本,您可以评估以完全删除这些 id
【解决方案2】:

更短的版本:

location.href = this.options[this.selectedIndex].value

【讨论】:

    【解决方案3】:

    thisdocument.getElementById('sortbyselecttop') 代替sortbyformtop.sortbyselecttop

    document.getElementById('sortbyselecttop').options[document.getElementById('sortbyselecttop').selectedIndex].value
    

    或者

    this.options[this.selectedIndex].value
    

    【讨论】:

      【解决方案4】:

      您为什么要在内联事件处理程序中执行此操作?

      我确信有可能做你想做的事——我认为你可能需要在你的选择元素上添加一个“名称”属性而不是一个 ID,但是有一个单独的函数可能更容易你有更多的灵活性 - 然后从你的事件处理程序中调用函数。

      onchange="doSomething();"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-31
        • 2016-08-07
        • 2019-01-07
        • 2020-01-28
        • 2021-10-24
        • 2014-10-17
        • 2022-01-10
        • 2019-12-24
        相关资源
        最近更新 更多