如何获得div的ID是否包含在内? [英] How to get ID of div javascript is contained within?

查看:79
本文介绍了如何获得div的ID是否包含在内?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 < div id = example>< script>(retrieve id)< / script>< / div> 

而且希望能够返回example。对不起,如果这之前已经问过,我没有检查,找不到它。谢谢!

解决方案

以下内容仅适用于同步加载脚本而不加载异步选项。
$ b

它只是计算加载时存在的脚本标记,假设它是当前最后一个脚本标记(这就是为什么异步可能会失败),然后查询其父节点,这是您的div。

 < div id =example> 
< script>
(function(){
var scripts = document.getElementsByTagName('script'),
myScript = scripts [scripts.length - 1]

console.log (myScript.parentNode.getAttribute('id'));
})();

< / script>

< / div>

http://jsfiddle.net/vy5Z7/1/


I want to insert javascript inside a div that will retrieve that div's ID, as such:

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

解决方案

The following will only work when you load the script synchronously and not with async option.

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 id="example">
  <script>
    (function () {
        var scripts = document.getElementsByTagName('script'),
            myScript = scripts[scripts.length - 1]

        console.log(myScript.parentNode.getAttribute('id')); 
     })();

</script>

</div>

http://jsfiddle.net/vy5Z7/1/

这篇关于如何获得div的ID是否包含在内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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