我可以从子跨度点击事件中获得父Div标记innerHTML吗?请参阅代码

Can I get the parent Div tag innerHTML from a child span click event see code

本文关键字:标记 Div innerHTML 代码 请参阅 事件 我可以      更新时间:2023-09-26
<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的小提琴(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>