2010-10-06 45 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