如何获取div元素的rowIndex单击

时间:2018-04-27 19:34:47

标签: javascript

我想得到我点击<div>的rowIndex。

<div id="parent" onClick="this.click()">
    <div id="1">
      <span text="22"></span>
    </div>
    <div id="2"><span text="32"></span></div>
    <div id="3"><span text="232"></span></div>
    <div id="4"><span text="242"></span></div>
    <div id="5"><span text="252"></span></div>
</div>

我正处于一个我点击<div>的阶段,让我说我有:

<div id="3"><span text="232"></div>

如何在<span>内的<div>内获取文字的ID和值?

2 个答案:

答案 0 :(得分:1)

使用Element.addEventListener()向容器(#parent)添加事件处理程序。触发处理程序时,请检查事件目标是否为范围Element.matches()

如果是,请使用Element.getAttribute()从父节点(div)获取id,从span获取text属性:

var container = document.getElementById('parent');

container.addEventListener('click', function(e) {
  if (!e.target.matches('#parent > div > span')) return;
  
  var id = e.target.parentNode.id;
  var text = e.target.getAttribute('text');
  
  console.log(id, text);
});
<div id="parent">
  <div id="1">
    <span text="22">1</span>
  </div>
  <div id="2"><span text="32">2</span></div>
  <div id="3"><span text="232">3</span></div>
  <div id="4"><span text="242">4</span></div>
  <div id="5"><span text="252">5</span></div>
</div>

答案 1 :(得分:0)

如果您使用 Jquery ,这将有效 [已测试]

$("#parent").find('span').each(function(){
        $(this).on('click', function(){
            console.log($(this).parent().attr('id'));
        });
    });

如果有任何问题,请告诉我

相关问题