2011-01-05 70 views
1

在腳本標記中沒有任何id屬性的JavaScript中,是否有任何方法可以獲取當前正在執行的腳本節點的父節點?在JavaScript中,我可以掌握腳本所在的節點嗎?

爲了說明我的意思,如果我想將img附加到文檔中,並且我想將該圖像附加到ID爲「div1_id」的div節點,我可以在不知道div的id的情況下執行此操作,或者必須將id =「_ scriptid」屬性添加到腳本標記中,如我在下面所做的那樣?

<script type="text/javascript"> 
    function fn1() 
    { 
     var my_img = document.createElement("img"); 
var t = document.getElementById("_scriptid"); 
if (t.parentNode) { 
    t.parentNode.appendChild(my_img); 
} else { 
    document.getElementsByTagName("body")[0].appendChild(my_img); 
} 
    } 
</script> 

<div id="_div1_id" name="_div1_name"> 
    <script type="text/javascript" id="_scriptid"> 
     fn1(); 
    </script> 
</div> 

這就是我想做的事:

<head> 
    <script type="text/javascript"> 
    function fn1() 
    { 
     var my_img = document.createElement("img"); 
var x = get the node that is the parent node of the current script tag, 
       and so that I can still separate this code out into a function 
       as shown here, I do not want the <head> tag returned, I want to 
       get the parent node of the script that called this function, i.e. 
       the node commented as "div1" below. 
x.appendChild(my_img); 
    } 
    </script> 
</head> 

<div> <!-- div1 --> 
    <script type="text/javascript"> 
     // Call a function to add an image to the enclosing node (div node in this example): 
     fn1(); 
    </script> 
</div> 

的原因,我想問的是,我讓別人告訴我,他們在IE8得到一個錯誤「HTML解析錯誤:無法修改父子元素關閉之前的容器元素(KB927917)「,我懷疑這可能是因爲我正在使用appendChild將圖像附加到body元素,並且body元素未關閉。知識庫文章建議,添加到直接父級(即使該標籤顯然未關閉)可以解決問題。

謝謝。

回答

0

嘗試分配你的代碼的功能,然後將其分配給在window.onload變量

0

我認爲,問題的解決方案可能是重新思考的問題。

首先,你說你遇到了IE8的問題。我的建議:使用像jQuery這樣的Javascript庫來處理所有這些針對瀏覽器的問題。

然後,你有一些內部腳本的div,你不想給div或腳本唯一的id。儘管如此,你必須在你的div中放置seomthing來調用這個函數。我的建議:改用類。

<div class="callFn1"></div> 

這是如何有用? 在與jQuery結合,這給你以下問題的解決方案:(」 callFn1" )

$(".callFn1").each(
    function() { 
    fn1(this); 
    }); 

以$您選擇所有選定包含該類‘callFn1’的所有元素,迭代。每元素並調用一個函數。這個函數用參數this調用fn1,它給你當前處理的元素。現在你只需要修改你的函數fn1:

function fn1(x)