簡體   English   中英

使用onclick屬性中的Javascript在html中獲取子元素標記

[英]Get a child element tag in html using Javascript in the onclick attribute

使用純JavaScript,我想通過使用父級的onclick屬性在<a>元素內引用第一個內部html元素。 我嘗試同時使用firstChildfirstChild.InnerHTML ,但無法獲取元素。

例如,以下html代碼:

<a href="#" onclick="showImg(this.firstChild.innerHTML)">
  <img src="imgs/placeholder.png" alt="My Image" title="image-name" >
  <p>This is a paragraph</p>
  <div>This is a div</div>
</a>

我想將<img>元素作為參數添加到函數showImg() ,因此我可以獲取title屬性以饋入要在模式窗口/彈出窗口中顯示的圖像路徑。

使用相同的功能BTW將顯示相同的模式窗口。

這有可能實現嗎? (請注意,我要獲取整個元素,而不僅僅是屬性。)

這樣做是因為沒有添加jquery或其他類似庫的權限。

更新:我正在尋找從版本7開始在IE上運行的代碼。

我的解決方案:根據此答案的詳細信息,在組合了firstElementChildchildren[0]之后,我最終使用了getAttribute方法。

我的最終解決方案如下所示:

<a href="javascript:void(0)" 
   onclick="showImg((this.firstElementChild || 
                     this.children[0]).getAttribute('title'))">
  <img src="imgs/placeholder.png" alt="My Image" title="image-name" >
  <p>This is a paragraph</p>
  <div>This is a div</div>
</a>

這是腳本:

  function getImg(img) {        
    var container = document.getElementById("some-id");
    var imgPath = 'imgs/' +img+ '.png';
    container.src = imgPath;
  }

感謝您的見解。

這應該可以解決問題:

 function showImg(image) { console.log(image); } 
 <a href="#" onclick="showImg(this.children[0].getAttribute('title'))"> <img src="imgs/placeholder.png" alt="My Image" title="image-name" > <p>This is a paragraph</p> <div>This is a div</div> </a> 

如果需要整個元素,則將onclick替換為: onclick="showImg(this.children[0])"

您應該使用getAttribute函數

<a href="#" onclick="showImg(this.firstElementChild.getAttribute('title')">

使用this.firstElementChild.outerHTML

<a href="#" onclick="alert(this.firstElementChild.outerHTML)">
  <img src="imgs/placeholder.png" alt="My Image" title="image-name" >
  <p>This is a paragraph</p>
  <div>This is a div</div>
</a>

暫無
暫無

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

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