【问题标题】:why doesn't this script work and...?为什么这个脚本不起作用并且......?
【发布时间】:2011-09-18 18:19:55
【问题描述】:

html代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="script.js">
</script>
</head>

<body bgcolor="#FFFFCC">
<center>
<form>
 <select id="newLocation">
  <option value="1.jpg">index</option>
   <option value="script.js">posts</option>
   <option value="2.jpg" selected="selected">blog</option>
 </select>
</form>

javascript:

window.onload = startInit;

function startInit() {
document.getElementById("newLocation").selectedIndex = 0;
document.getElementById("newLocation").onchange = jumpPage;
}

function jumpPage() {
var newLoc = document.getElementById("newLocation");// what does this statement return ?
var newPage = newLoc.options[newLoc.getSelectedIndex].value;
if(newPage != "")
   window.location = newPage;
}

为什么不进入新页面,即当我从组合框中选择一个选项时的值? 还有document.getElementById("newLocation");这个语句(函数jumpPage的第一条语句)返回什么?

【问题讨论】:

  • 诊断此类问题的常用方法是调试。使用console.logalert() 进行测试输出,看看哪里出了问题。这样,您还可以自己找出您所询问的该行返回的内容
  • @Pekkai 尝试过该方法但不理解输出。它返回object HTML select element。我不明白这个。
  • 如果你真的想学习如何做到这一点,那么可以问一个关于这个的问题。这比找出当前脚本中的问题要高效得多
  • 有什么不明白的?如果您通过 ID 获取元素,那么您将获取该元素。

标签: javascript


【解决方案1】:

你可以试试

var newPage = newLoc.options[newLoc.selectedIndex].value;

声明

var newLoc = document.getElementById("newLocation"); 

只找到 DOM (HTML) 元素 &lt;... id="newLocation" ...&gt;,即您的 &lt;select id="newLocation"&gt;

【讨论】:

    【解决方案2】:

    document.getElementById("newLocation") 将返回 SELECT 对象(即对下拉列表的引用)。

    关于JS,它有一个错误。您应该将newLoc.getSelectedIndex 更改为newLoc.selectedIndex

    【讨论】:

      猜你喜欢
      • 2015-06-16
      • 2020-12-14
      • 2013-10-20
      • 2014-09-24
      • 1970-01-01
      • 1970-01-01
      • 2014-09-18
      • 2018-10-25
      • 2021-08-29
      相关资源
      最近更新 更多