嗨我有几个div元素,如下图所示:
<div class="div-bubble bubble">
<p>This is the text I would like to get</p>
<ul>
<li>
<a href="#" class="action-link action" id="linkId">Yes</a>
</li>
<li>
<a href="#" class="action-link action" id="linkId">No</a>
</li>
</ul>
</div>
如果我点击li元素中的yes或no链接,我怎么能得到上面的p元素?它一定是在香草js。
答案 0 :(得分:0)
尝试下面的代码段,
function linkClick(e, id){ console.log(document.getElementById(id).closest('div').childNodes[1])
}
&#13;
<div class="div-bubble bubble">
<p>This is the text I would like to get</p>
<ul>
<li>
<a href="#" onClick="linkClick(event, this.id)" class="action-link action" id="1">Yes</a>
</li>
<li>
<a href="#" class="action-link action" id="2">No</a>
</li>
</ul>
</div>
&#13;
答案 1 :(得分:0)
我建议你做这样的事情:
(唯一添加的是JavaScript,我没有修改你的HTML)
var links = document.getElementsByClassName('action-link');
for (var i = 0; i < links.length; i++) {
links[i].addEventListener("click", function() {
console.log(this.closest('div').getElementsByTagName('p')[0].innerHTML);
});
}
&#13;
<div class="div-bubble bubble">
<p>This is the text I would like to get</p>
<ul>
<li>
<a href="#" class="action-link action" id="1">Yes</a>
</li>
<li>
<a href="#" class="action-link action" id="2">No</a>
</li>
</ul>
</div>
&#13;
最好不要使用内联javascript。
希望它有所帮助。