Chrome和Opera中的选项选择问题

Problems with option selection in Chrome and Opera

本文关键字:选项 选择 问题 Opera Chrome      更新时间:2023-09-26

我对这个代码有问题,它在Firefox和Internet Explorer中运行良好,但在Opera和Chrome浏览器中不起作用。。。

<script>
function planetselect()
{
optionen=document.getElementById('pstart').options;
for(i=0;i<optionen.length;i++)
{
if(optionen[i].value==67080)
{
  optionen[i].setAttribute('selected','selected');
  }
}
optionen=document.getElementById('pdest').options;
for(i=0;i<optionen.length;i++)
{
if(optionen[i].value==67080)
{
  optionen[i].setAttribute('selected','selected');
  }
}
}</script>

更改

optionen[i].setAttribute('selected','selected');

optionen[i].selected = true;

更一般地说,避免使用setAttribute来更改DOM属性。有时有效,有时无效。

来自MDN:

使用setAttribute()修改某些属性,尤其是值在XUL中,工作不一致,因为属性指定了默认值价值要访问或修改当前值,应使用属性。例如,使用elt.value而不是elt.setAttribute('value',val)。

是否确保关闭了<script>标记?我看不出你发布的代码有什么问题,所以要么你没有关闭标签,要么你的optionenoptions变量不在那里,或者无效

同样,您应该知道chrome有一个javascript控制台,它应该向您显示任何错误。打开它,它是ctrl-shift-j。这应该对你有很大帮助。