[英]Can I get the parent Div tag innerHTML from a child span click event see code
<body>
<div class='Myclass'>
Value I Want, I have already got the span inner html, but I want to add the the value of the div
<span onclick='Some javascript to get div value'>some html</span>
</div>
</body>
告訴我是否可以改善此答案。
請感謝@JoshCrozier的jsfiddle( https://jsfiddle.net/1p2j4em7/ ),它為該答案提供了一些新信息,力求做到最好。
function getText(elem){ alert(elem.previousSibling.nodeValue.trim()) }
<body> <div class='Myclass'> Value I Want, I have already got the span inner html, but I want to add the the value of the div <span onclick='getText(this);'>some html</span> </div> </body>
這是一個通用的解決方案,可用於所需的多個div。
window.addEventListener('load', function() { var divs = document.getElementsByClassName('Myclass'); for (var i = 0; i < divs.length; i++) { divs[i].children[0].onclick = function() { alert(this.previousSibling.nodeValue.trim()) } } });
<body> <div class='Myclass'> Value I Want, I have already got the span inner html, but I want to add the the value of the div <span onclick='getText(this);'>some html</span> </div> </body>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.