是否可以从被调用函数的位置获取父元素?
我的情况:
<div class="alphabet">
<div class="lorem">
<script type="text/javascript">
getParent();
</script>
</div>
<div class="ipsum">
<script type="text/javascript">
getParent();
</script>
</div>
<div class="dolor">
<div class="amet">
<script type="text/javascript">
getParent();
</script>
</div>
</div>
</div>
<script>
function getParent(){
//......????????.......//
}
</script>
预期结果(控制台日志):
答案 0 :(得分:1)
这应该有用,虽然我的直觉告诉我你做错了什么。
<script>
function getParent(){
var me = document.currentScript;
var parent = me.parentElement;
console.log(parent.className);
return parent;
}
</script>
<div class="lorem">
<script type="text/javascript">
getParent();
</script>
</div>
<div class="ipsum">
<script type="text/javascript">
getParent();
</script>
</div>