按类名获取祖先

时间:2015-07-30 18:15:04

标签: javascript html html5 google-closure-library

我有一个组件,其中包含按钮和列表,这些按钮和列表都在点击时执行事件。我需要一种通用的方法来获取这些元素的祖先元素。结构看起来像

<div class='a'>
   <button class ='b' data-name="hello">
      <span class ='c'>clickMe
         <span>somehting</span>
      </span>
   <button>
   <ul class ='d'>
      <li data-name="about">
          <span class ='e'>something here
             <span>somehting</span>
          </span>
      </li>
      <li data-name="home">
          <span class ='e'>something elser here
              <span>somehting</span>
          </span>
      </li>
   </ul>
</div>

我尝试获取元素按钮和li,因为我需要获取数据名称信息。 e.target是被点击的元素

var targetel = goog.dom.getAncestorByClass(e.target,null,class??);

不知道如何获得正确的元素,无论其是按钮还是li。我是否需要为所有元素添加一个唯一的类?

2 个答案:

答案 0 :(得分:2)

只需使用e.currentTarget

即可

var result = document.querySelector('#result');
var clickables = document.querySelectorAll('button, li');

//add click listener to elements
for (var i = 0, l = clickables.length; i < l; i++) {
  clickables[i].addEventListener('click', getDataName);
}

function getDataName(e) {
  var dataName = e.currentTarget.getAttribute('data-name');
  
  result.textContent = dataName;
}
<div class='a'>
   <button class ='b' data-name="hello">
      <span class ='c'>clickMe
         <span>somehting</span>
      </span>
   </button>
   <ul class ='d'>
      <li data-name="about">
          <span class ='e'>something here
             <span>somehting</span>
          </span>
      </li>
      <li data-name="home">
          <span class ='e'>something elser here
              <span>somehting</span>
          </span>
      </li>
   </ul>
</div>

<div id="result">data-name of clicked element goes here</div>

答案 1 :(得分:-1)

https://api.jquery.com/parents/

使用jquery.parents(“li”)函数。它将选择与您的css过滤器匹配的所有父项。所以你可以做到

var parentli = targete1.parents("li");

var button = targete1.parents("div").children[0];

或类似的东西。

编辑: 不知道为什么我被投票,这是我的想法。

也许按f12检查元素并查看控制台日志。

var onClick = function () {
    var parentEl = $(this).parents("button, li")[0];
    console.log(parentEl);
    $("#result")[0].innerText = parentEl.getAttribute("data-name");
};

$('span.c').click(onClick);

$('li span.e').click(onClick);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='a'>
   <button class='b' data-name="hello">
      <span class='c'>clickMe
         <span>something</span>
      </span>
    </button>
   <ul class ='d'>
      <li data-name="about">
          <span class ='e'>something here
             <span>somehting</span>
          </span>
      </li>
      <li data-name="home">
          <span class ='e'>something elser here
              <span>something</span>
          </span>
      </li>
   </ul>
</div>
<div id="result">result goes here</div>