Javascript中当前的元素是什么? [英] What is the current element in Javascript?

查看:91
本文介绍了Javascript中当前的元素是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何查看元素是否位于< script> 中?

举个例子, p>

How can I find out what the element is that a <script> sits in?
As an example, let's take this

<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>

那么如果我想把它改成更现代的东西,我怎么能找出我们的什么元素重新进入?

所以我想写,例如在jQuery

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

$(thisdiv).html('It is '+hrs+":"+(min<10?'0':'')+min);

但是如何获得 thisdiv ? br>
是的,我知道,我可以在其上放一个ID,但我有这样的感觉,这是没有必要的。浏览器知道我们在哪里,否则它甚至不能做document.write!

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!

那么建议?我搜索,但找不到。是这么简单,我忽略了明显的?

So, suggestions? I searched, but couldn't find it. Is it so simple that I'm overlooking the obvious?

推荐答案

脚本按照文档中出现的顺序执行。脚本标签的内容在遇到时进行评估,因此最后一个< script> 元素始终是当前的。

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.

代码:

<div>
  <script>
    var scriptTag = document.getElementsByTagName('script');
    scriptTag = scriptTag[scriptTag.length - 1];

    var parent = scriptTag.parentNode;
  </script>
</div>

这篇关于Javascript中当前的元素是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆