Javascript 中的当前元素是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9209823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the current element in Javascript?
提问by Mr Lister
How can I find out what the element is that a <script>
sits in?
As an example, let's take this
如何找出 a<script>
所在的元素?
举个例子,让我们拿这个
<div>
<script type="text/javascript">
var time = new Date(), hrs = time.getHours(), min = time.getMinutes();
document.write('It is '+hrs+":"+(min<10?'0':'')+min);
</script>
</div>
Then if I want to change this to something more modern, how can I find out what element we're in?
So I want to write, for instance in jQuery
那么如果我想把它改成更现代的东西,我怎么能找出我们所在的元素呢?
所以我想写,例如在 jQuery
$(thisdiv).html('It is '+hrs+":"+(min<10?'0':'')+min);
but how do I get thisdiv
?
Yes, I know, I can put an ID on it, but I have the feeling that wouldn't be necessary. The browser knows where we are, otherwise it couldn't even do the document.write!
但我怎么得到thisdiv
?
是的,我知道,我可以在上面放一个 ID,但我觉得没有必要。浏览器知道我们在哪里,否则它甚至无法执行 document.write!
So, suggestions? I searched, but couldn't find it. Is it so simple that I'm overlooking the obvious?
那么,建议?我搜索过,但找不到。是否如此简单以至于我忽略了显而易见的事情?
回答by Rob W
Script are executed in the order of appearance in the document. The contents of a script tag are evaluated on encounter, so, the last <script>
element is always the current one.
脚本按照在文档中出现的顺序执行。脚本标记的内容在遇到时进行评估,因此最后一个<script>
元素始终是当前元素。
Code:
代码:
<div>
<script>
var scriptTag = document.getElementsByTagName('script');
scriptTag = scriptTag[scriptTag.length - 1];
var parent = scriptTag.parentNode;
</script>
</div>
回答by Phil H
Firefox:
火狐:
document.currentScript.parentElement
Chrome:
铬合金:
document.scripts.length
回答by osahyoun
$('script#some_id').parent().html('blah blah');
回答by Mujtaba Haider
Try this
试试这个
<div id="mydiv">
<script type="text/javascript">
var time = new Date(), hrs = time.getHours(), min = time.getMinutes();
document.getElementById('mydiv').innerHTML = 'It is '+hrs+":"+(min<10?'0':'')+min;
</script>
</div>