我可以从子跨度点击事件中获得父Div标记innerHTML吗?请参阅代码
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的小提琴(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>
相关文章:
- 如何将DIV标记的内容拆分为多个DIV
- 如何使用Jquery在DIV标记内创建表
- 在 DIV 标记中动态加载页面
- 小程序上的Div标记
- 如何使JavaScript只在特定的DIV标记中起作用
- 从一个正在运行的PHP代码中,了解如何更新DIV标记中的状态
- For循环只打印一个DIV标记.不是8个DIV标签
- Div/Class 中的 html 标记
- 如果文本为 0,JavaScript 隐藏 DIV 标记
- 将 UI 模式对话框添加到新的 DIV 标记
- 使用 jquery 跟踪 DIV 标记下的 HTML 表单控件中的数据更改
- 选中复选标记时增加 Div 高度
- 如果 Div 放置在 img 标记的顶部,则不会在 Div 上触发鼠标关闭事件 - 问题仅在 IE 中
- 计算没有名称或 ID 的通用 DIV 标记
- 通过复选标记显示 Div
- 如何使用 AJAX 打开 DIV 标记内的 URL
- Div 标记不显示任何结果
- 正在转换<br>标记到<Div>或者<P>标签
- 我可以从子跨度点击事件中获得父Div标记innerHTML吗?请参阅代码
- 将带有HTML标记的内容粘贴到Contenteditable DIV