问题描述
我处于一种似乎必须在javascript库中使用document.write的情况。脚本必须知道定义脚本的区域的宽度。但是,该脚本对该区域中的任何标记都没有任何明确的知识。如果有明确的div知识那么它就会这么简单:
I am in a situation where it seems that I must use document.write in a javascript library. The script must know the width of the area where the script is defined. However, the script does not have any explicit knowledge of any tags in that area. If there were explicit knowledge of a div then it would be as simple as this:
<div id="childAnchor"></div>
<script ref...
//inside of referenced script
var divWidth = $("#childAnchor").width();
</script>
因此,在引用的脚本中,我正在考虑使用document.write这样:
So, inside of the referenced script, I am thinking of doing using document.write like this:
<script ref...
//inside of referenced script
var childAnchor = "z_87127XNA_2451ap";
document.write('<div id="' + childAnchor + '"></div>');
var divWidth = $("#" + childAnchor).width();
</script>
但是,我真的不喜欢document.write实现。有没有替代在这里使用document.write?我不能简单地使用窗口的原因是它在一个视图内部,在一个主视图页面内呈现。窗口无法正确获得嵌套区域宽度。
However, I do not really like the document.write implementation. Is there any alternative to using document.write here? The reason that I cannot simply use window is that this is inside of a view which is rendered inside of a master view page. Window would not properly get the nested area width.
该区域几乎就在这里:
<body>
<div>
<div>
<div>
AREA
AREA不了解任何其他div。
The AREA has no knowledge of any of the other divs.
推荐答案
这件事刚刚发生在我身上,我记得你的问题:脚本代码可以找到它所在的脚本块,所以你可以遍历从那里的DOM。当前脚本块将是DOM中最后一个(当代码运行时DOM仍然被解析)。
This just occurred to me, and I remembered your question: the script code can find the script block it is in, so you can traverse the DOM from there. The current script block will be the last one in the DOM at the moment (the DOM still being parsed when the code runs).
通过查找当前脚本块,您可以找到其父元素,并在任何地方添加新元素:
By locating the current script block, you can find its parent element, and add new elements anywhere:
<!doctype html>
<html>
<head>
<style>
.parent .before { color: red; }
.parent .after { color: blue; }
</style>
</head>
<body>
<script></script>
<div class="parent">
<span>before script block</span>
<script>
var s = document.getElementsByTagName('script');
var here = s[s.length-1];
var red = document.createElement("p");
red.className = 'before';
red.innerHTML = "red text";
here.parentNode.insertBefore(red, here);
var blue = document.createElement("p");
blue.className = 'after';
blue.innerHTML = "blue text";
here.parentNode.appendChild(blue);
</script>
<span>after script block</span>
</div>
<script></script>
</body>
</html>
注意蓝色文字span将在脚本块后跨度之前插入。那是因为当前调用 appendChild
时,DOM中不存在after跨度。
Note the "blue text" span will be inserted before the "after script block" span. That's because the "after" span does not exist in the DOM at the moment appendChild
is called.
但。
这篇关于document.write的替代品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!