簡體   English   中英

在JavaScript中,我能否掌握腳本所在的節點?

[英]In JavaScript, can I get hold of the node that script is enclosed in?

JavaScript中有什么方法可以在腳本標簽上沒有id屬性的情況下獲取當前執行的腳本節點的父節點?

為了說明我的意思,如果我想將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元素未關閉。 KB文章建議添加到直接父級(即使該標簽顯然沒有關閉)也可以解決此問題。

謝謝。

嘗試將代碼分配給一個函數,然后將其分配給window.onload變量

我認為解決您的問題的方法可能是重新考慮問題。

首先,您說您遇到了IE8問題。 我的建議:使用類似jQuery的Javascript庫為您處理所有這些特定於瀏覽器的陷阱。

然后,您有一些帶有腳本的div,而您不想給div或腳本唯一的ID。 盡管如此,您仍然必須在div中放入seomthing才能調用該函數。 我的建議:改用類。

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

這有什么用? 與jQuery結合使用,可以為您的問題提供以下解決方案:

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

使用$(“。callFn1”)選擇包含類“ callFn1”的所有元素。.each迭代所有選定的元素並調用函數。 該函數使用參數this調用fn1-它為您提供了當前正在處理的元素。 您現在所要做的就是修改函數fn1,如下所示:

function fn1(x)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM