Gibt es in JavaScript eine Möglichkeit, den übergeordneten Knoten des aktuell ausgeführten Skriptknotens zu erhalten, ohne ein ID-Attribut für das Skript-Tag zu haben?Kann ich in JavaScript den Knoten erhalten, in dem das Skript eingeschlossen ist?
Um zu veranschaulichen, was ich meine, wenn ich ein IMG an das Dokument anhängen möchte, und ich dieses Bild an den Div-Knoten mit der ID "div1_id" anhängen möchte, kann ich das tun, ohne die ID des div zu kennen. oder muss das Attribut "id =" _ scriptid "zum Script-Tag hinzugefügt werden, wie ich es unten tun musste?
<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>
Hier ist, was ich tun möchte:
<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>
Der Grund, warum ich frage ist, dass ich jemand bin immer mir zu sagen, sie einen Fehler in IE8 „HTML-Parsing-Fehler erhalten: Kann nicht die Eltern ändern container-Element, bevor das untergeordnete Element geschlossen wird (KB927917) "und ich nehme an, dass es daran liegt, dass ich appendChild verwende, um ein Bild an das body-Element anzuhängen, und das body-Element nicht geschlossen ist. Der KB-Artikel schlägt vor, dass das Hinzufügen zu dem direkten Eltern (obwohl das Tag offensichtlich nicht geschlossen ist) das Problem behebt.
Danke.