找到JavaScript正在运行的标签 [英] Find the tag JavaScript is running in
问题描述
在后端生成HTML源代码,我使用了独立的独立窗口小部件。
我只是将这样的标记包含在HTML输出中。
< div>
我想使用这个DOM元素
< script>
new Obj(/ *但我无法获取这个< div>作为参数!* /);
< / script>
< / div>
我正在寻找一种方法来查找其中 obj
被创建(没有任何唯一的ID)。这将为我的应用增加灵活性并加速开发。但是,在JavaScript中是否可能存在技术问题?
以下代码有效:
< script>函数Obj(color){var scriptTags = document.getElementsByTagName(script); var scriptTag = scriptTags [scriptTags.length - 1]; //找到父母或做任何事var divTag = scriptTag.parentNode; divTag.style.backgroundColor = color; }< /脚本>< DIV>我想使用这个DOM元素< script> new Obj(green);< / script>< / div>< div>我想使用这个DOM元素< script> new Obj(yellow);< / script>< / div>< div>我想用这个DOM元素< script> new Obj(lime);< / script>< / div>
div>
这个方法有非常简单的代码,对性能影响几乎没有。
注意:我是很确定这不会工作的IE6(据我记得它不支持操纵打开标签)。
Generating HTML source on backend, I am using separate independent widgets.
I am simply including pieces of markup like this to the resulting HTML output.
<div>
I want to work with this DOM element
<script>
new Obj(/*but I can't get this <div> as a parameter! */);
</script>
</div>
I'm looking for a way to find the DOM element in which the obj
is created (Without any unique IDs). This would add flexibility to my app and speed up the development. But is that technicaly possible in JavaScript?
The following code works:
<script>
function Obj(color) {
var scriptTags = document.getElementsByTagName("script");
var scriptTag = scriptTags[scriptTags.length - 1];
// find parent or do whatsoever
var divTag = scriptTag.parentNode;
divTag.style.backgroundColor = color;
}
</script>
<div>
I want to work with this DOM element
<script>new Obj("green");</script>
</div>
<div>
I want to work with this DOM element
<script>new Obj("yellow");</script>
</div>
<div>
I want to work with this DOM element
<script>new Obj("lime");</script>
</div>
This method has very simple code and has almost zero impact on performance.
Note: I am pretty sure this won't work IE6 (as far as I remember it does not support manipulating open tags).
这篇关于找到JavaScript正在运行的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!