Javascript 中当前的元素是什么?
如何找出 所在的元素是什么?
举个例子,
<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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
脚本按照文档中出现的顺序执行。脚本标记的内容是在遇到时评估的,因此,最后一个
元素始终是当前元素。
代码:
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:
火狐浏览器:
铬:
Firefox:
Chrome:
试试这个
Try this