如何获取包含在其中的 div javascript 的 ID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14263717/
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
How to get ID of div javascript is contained within?
提问by user1790093
I want to insert javascript inside a div that will retrieve that div's ID, as such:
我想在将检索该 div 的 ID 的 div 中插入 javascript,如下所示:
<div id="example"><script>(retrieve id)</script></div>
And that would hopefully return "example". Sorry if this has been asked before, I did check and couldn't find it. Thanks!
这将有望返回“示例”。抱歉,如果之前有人问过这个问题,我确实检查过但找不到。谢谢!
回答by Robin Drexler
The following will only work when you load the script synchronously and not with async option.
以下仅当您同步加载脚本而不是使用 async 选项时才有效。
It simply counts the script tags that do exist when it's loaded, assumes that it's currently the last one (that's why async would probably fail) and then it's querying its parent node, which is your div.
它只是计算加载时确实存在的脚本标签,假设它当前是最后一个(这就是异步可能会失败的原因),然后查询其父节点,即您的 div。
<div id="example">
<script>
(function () {
var scripts = document.getElementsByTagName('script'),
myScript = scripts[scripts.length - 1]
console.log(myScript.parentNode.getAttribute('id'));
})();
</script>
</div>
回答by isherwood
Are you able to put an id on the script tag?
你能在脚本标签上放一个 id 吗?
<div id="example">
<script id="myScript">
var myScript = document.getElementById('myScript');
var myId = myScript.parentNode.id;
alert(myId);
</script>
</div>