簡體   English   中英

如何獲得div元素的rowIndex單擊

[英]How to get the rowIndex of a div element clicked

我想獲取單擊的<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>

如何獲取<div> <span>本的ID和值?

使用Element.addEventListener()將事件處理程序添加到容器( #parent Element.addEventListener() 觸發處理程序時,檢查事件目標是否為span Element.matches()

如果是這樣,請使用Element.getAttribute()從父節點(div)獲取id ,並從跨度獲取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> 

如果您使用的是Jquery ,則可以使用[已測試]

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

讓我知道是否有任何問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM