简体   繁体   English

Javascript函数无法按预期在IE中运行

[英]Javascript function not working as expected in IE

This code below works fine in chrome, Firefox and Edge. 下面的代码在chrome,Firefox和Edge中可以正常工作。 But when I try this same code in html I get the following error. 但是,当我在html中尝试相同的代码时,出现以下错误。

SCRIPT5009: 'ddlTest' is undefined SCRIPT5009:“ ddlTest”未定义

<select id="ddlTest">
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>

<script>

    function testFunc() {
        var y = (ddlTest).value;
        alert(y);
    }

</script>

Is there a way I can get around this in IE , other than doing : 除了这样做,我是否可以在IE中解决此问题:

document.getElementById('ddlTest').value 的document.getElementById( 'ddlTest')。值

The feature to have a property on window to access an element by ID was added in HTML5. 在HTML5中添加了在window上具有通过ID访问元素的属性的功能。

The HTML5 standard specifies that the window object must have a property key whose value is elem if... HTML5标准指定在以下情况下,窗口对象必须具有属性键,其值是elem

  • there is exactly one DOM element elem whose property id has the value key . 刚好有一个DOM元素elem,其属性id为value
  • there is exactly one DOM element elem whose property name has the value key . 刚好有一个DOM元素elem,其属性名称具有值key elem ’s tag must be one of: a, applet, area, embed, form, frame, frameset, iframe, img, object. elem的标签必须是以下之一:a,applet,区域,嵌入,表单,框架,框架集,iframe,img,对象。

~ http://2ality.com/2012/08/ids-are-global.html 〜http://2ality.com/2012/08/ids-are-global.html

However, you should not use this in your actual code -- use document.getElementByID('elem') instead: 使用-然而,你应该在你的实际代码使用document.getElementByID('elem')代替

As a general rule, relying on this will lead to brittle code. 通常,依靠它会导致代码变脆。 Which IDs end up mapping to this API can vary over time, as new features are added to the Web platform, for example. 例如,随着新功能添加到Web平台,最终映射到该API的ID会随时间变化。 Instead of this, use document.getElementById() or document.querySelector() . 代替此,使用document.getElementById()document.querySelector()

~ https://html.spec.whatwg.org/#named-access-on-the-window-object 〜https ://html.spec.whatwg.org/#named-access-on-the-window-object

No, the only way to do it is to get the element through the document: 不,唯一的方法是通过文档获取元素:

function testFunc() {
    var ddlTest = document.getElementById('ddlTest');
    var y = ddlTest && ddlTest.value;
    alert(y);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM