Javascript 中当前的元素是什么?

发布于 2025-01-04 07:23:17 字数 612 浏览 0 评论 0原文

如何找出

<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 来编写,

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

但是如何获取 thisdiv
是的,我知道,我可以在上面贴上身份证,但我感觉没有必要。浏览器知道我们在哪里,否则它甚至无法执行 document.write!

那么,建议?我搜索过,但没有找到。难道它是如此简单以至于我忽略了显而易见的事情吗?

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>

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

极度宠爱 2025-01-11 07:23:17

脚本按照文档中出现的顺序执行。脚本标记的内容是在遇到时评估的,因此,最后一个

代码:

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

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

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.

Code:

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

    var parent = scriptTag.parentNode;
  </script>
</div>
回眸一遍 2025-01-11 07:23:17

火狐浏览器:

document.currentScript.parentElement

铬:

document.scripts.length

Firefox:

document.currentScript.parentElement

Chrome:

document.scripts.length
等风也等你 2025-01-11 07:23:17
$('script#some_id').parent().html('blah blah');
$('script#some_id').parent().html('blah blah');
等你爱我 2025-01-11 07:23:17

试试这个

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

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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文