2010-10-06 69 views
2

我有了这个DOCTYPE HTML页面:如何通过javascript在IE8中获得非标准属性?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 

然而,HTML包含本文标签:

<applet src="blahblah"></applet> 

(编辑:实际上在HTML中不包含applet的小程序由其他JavaScript代码动态创建)。

是的,我知道applet已过时,并且我知道applet标记不能包含src属性,但我无法编辑该HTML代码。

问题是这样的Javascript代码:

alert(appletElement.getAttribute('src')); 

在FF和Chrome显示 “blahblah”,但在IE8它显示null。另外,appletElement.attributes['src']未定义。

任何人都知道如何在严格模式下获得IE8中的src属性?

感谢IE8

回答

0

我已经找到了解决办法。

而不是使用document.createElement动态创建的小程序,我用这个函数:

function wrs_createElement(elementName, attributes, creator) { 
    if (attributes === undefined) { 
     attributes = {}; 
    } 

    if (creator === undefined) { 
     creator = document; 
    } 

    var element; 

    /* 
    * Internet Explorer fix: 
    * If you create a new object dynamically, you can't set a non-standard attribute. 
    * For example, you can't set the "src" attribute on an "applet" object. 
    * Other browsers will throw an exception and will run the standard code. 
    */ 

    try { 
     var html = '<' + elementName + ' '; 

     for (var attributeName in attributes) { 
      html += attributeName + '="' + attributes[attributeName].split('"').join('\\"') + '" '; 
     } 

     html += '>'; 
     element = creator.createElement(html); 
    } 
    catch (e) { 
     element = creator.createElement(elementName); 

     for (var attributeName in attributes) { 
      element.setAttribute(attributeName, attributes[attributeName]); 
     } 
    } 

    return element; 
} 
3
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 
           "http://www.w3.org/TR/html4/strict.dtd"> 
<title>Test Case</title> 
<applet id="myapplet" src="blahblah"></applet> 
<script> 
var aplt = document.getElementById('myapplet'); 
alert(aplt.getAttribute('src')); 
</script> 

为我工作。

+0

好吧,我是不是在我的问题的真诚。 applet对象没有插入到HTML中,而是使用document.createElement动态创建的。当您将不标准的属性设置为该小程序时,以后将无法检索它。它永远返回'null'。 – Nitz 2010-10-07 09:24:19

0

你试过

appletElement.src 
+0

它不工作:( – Nitz 2010-10-07 09:25:53

相关问题