我想获取 <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>
中文本的id和值里面<div>
?
最佳答案
使用 Element.addEventListener()
将事件处理程序添加到容器 (#parent
) 。当处理程序被触发时,检查事件目标是否是一个span Element.matches()
.
如果是,则从父节点(div)获取id
,并使用Element.getAttribute()
从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>
关于javascript - 如何获取点击的div元素的rowIndex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50069197/