简体   繁体   English

如何获取从中调用javascript函数的html链接的父div的类名?

[英]How to get class name of parent div of html link from which javascript function is called?

How can I get the class name of the parent div from which a html link calls a javascript function? 如何获取父div的类名称,HTML链接从该类调用javascript函数?

In the following code example: 在以下代码示例中:

<div class="parent-class">
  <a href="javascript:parent(this.parent)">Find parent</a>
</div>

<script>
  function parent(parent) {
    var theValueImLookingFor = (parent.className);
  }
</script>

I would like the "theValueImLookingFor" to be "parent-class", but I keep getting "undefined". 我希望“ theValueImLookingFor”是“父类”,但我一直在获取“未定义”。

I been trying to figure this out for almost an hour, what can I change to make this work? 我试图解决这个问题将近一个小时,该如何改变才能使它正常工作? I understand there are more static ways to get this information, but for my specific purpose I really need to identify the div through the javascript function from which it is called. 我知道有更多静态方法可以获取此信息,但是出于我的特定目的,我确实需要通过调用它的javascript函数来识别div。

You've tagged this with jQuery, which will be the easiest way to find the details of the parent div. 您已使用jQuery标记了此名称,这将是查找父div详细信息的最简单方法。 Something like 就像是

<div class="parent-div">
    <a id="link">Find Parent</a>
</div>

<script>
    $('#link').click(function() {
        alert($(this).parent().attr('class'));
    });
</script>

I would avoid using JavaScript as an href value, and do something like this: 我会避免将JavaScript用作href值,并执行以下操作:

var pre = onload;
onload = function(){
if(pre)pre();

var doc = document;
function getParentClassName(childNode){
  return childNode.parentNode.className;
}
console.log(getParentClassName(doc.getElementsByTagName('a')[0]));

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM