【问题标题】:On select javascript not working with pull down?在选择 javascript 上不能使用下拉?
【发布时间】:2011-07-13 19:36:14
【问题描述】:

我是 JavaScript 新手。

我修改了一个功能,当用户从下拉菜单中选择“是”时,它会在 div 区域中创建 3 个文本框。

这是我的表单下拉代码:

    <select name="dosage" id="dosage" onchange="function dosage(sel)">
            <option value="No">No</option>
            <option value="Yes">Yes</option> 

    </select>
<div id="dosagearea"></div>

这是我修改的 javascript,它最初在用户选择某些内容时创建了一个消息框。

    function dosage(sel)
{
   if(sel.options.selectedIndex == 0)
   {

      return false;
   }


    else if(sel.options.selectedIndex == 'Yes')
       {
          x=document.createElement('input');
                    x.setAttribute('rows',1);
                    x.setAttribute('cols',20);
                    x.name='dosage_emitted';
                    document.getElementById('dosagearea').appendChild(x);

            x=document.createElement('input');
                    x.setAttribute('rows',1);
                    x.setAttribute('cols',20);
                    x.name='dosage_absorbed';
                    document.getElementById('dosagearea').appendChild(x)


            x=document.createElement('input');
                    x.setAttribute('rows',1);
                    x.setAttribute('cols',20);
                    x.name='dosage_period';
                    document.getElementById('dosagearea').appendChild(x)
       }
    } 

我检查了 firebug 并没有返回 JS 错误,我认为我的函数没有被正确调用。

谢谢

【问题讨论】:

  • 你也不需要添加 rows 属性。这是文本区域标签

标签: javascript html onselect


【解决方案1】:

onchange 属性的值基本上是一个函数或一些 JavaScript 的名称。如果你想用select元素作为参数调用你的函数,你需要这样做

<select name="dosage" id="dosage" onchange="dosage(this)">

请注意,这不是推荐的做事方式,因为它将您的 HTML 与您的 JS 结合在一起。相反,尝试直接在 JS 中添加事件,像这样

window.onload = function() {
    document.getElementById("dosage").onchange = dosage;
    function dosasage(event) {
        var sel = event.currentTarget;
    }
}

【讨论】:

  • 嗨我试过你的建议,但它在萤火虫中说:document.getElementById("dosage").onchange = dose;错误:document.getElementById("dosage") 为空
  • 您可能在 DOM 准备好之前调用了 JavaScript。尝试将我提到的代码放在 window.onload 函数中。我更新了我的示例。
【解决方案2】:

尝试以下操作:onchange="dosage(this)"

【讨论】:

  • 谢谢,但现在萤火虫说错误:剂量不是函数
【解决方案3】:

最好在输入或占位符上使用 display:none 的 html 中已有的字段。并在选择yes 时切换到显示:阻止。此外,您需要将事件侦听器更改为 onchange="dosage(this)"

或者变成这样

<select name="dosage" id="dosage" onchange="document.getElementById('dosagearea').style.display = this.options.selectedIndex ? 'block' : 'none'">
   <option value="No">No</option>
   <option value="Yes">Yes</option> 
</select>
<div id="dosagearea" style="display:none">
    <input type="text" name="dosage_emitted" />
    <input type="text" name="dosage_absorbed" />
    <input type="text" name="dosage_period" />
</div>

它正在行动http://jsfiddle.net/t4cy7/

【讨论】:

  • 谢谢我更喜欢你的方式,它很简单并且本地化到页面。你是赢家!
猜你喜欢
  • 1970-01-01
  • 2013-07-29
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 2021-06-16
  • 1970-01-01
  • 2014-08-08
  • 1970-01-01
相关资源
最近更新 更多