使用纯 javascript,我想引用 <a>
中的第一个内部 html 元素元素,通过使用父级的 onclick
属性。我尝试同时使用 firstChild
和 firstChild.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 属性以输入要在模式窗口/弹出窗口中显示的图像路径。
顺便说一句,使用相同的函数将显示相同的模态窗口。
这有可能实现吗? (请注意,我想获取整个元素,而不仅仅是一个属性。)
这样做是因为没有添加 jquery 或其他类似库的权限。
更新:我正在寻找适用于 IE 7 以上版本的代码。
我的解决方案:
我终于结束了使用 getAttribute 方法,先将两者结合起来 firstElementChild
和 children[0]
根据 this answer 中的详细信息.
我的最终解决方案如下所示:
<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])"
关于javascript - 在onclick属性中使用Javascript获取html中的子元素标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33003640/