考虑这个HTML代码:
<div id="container">
<div class="c1">Text1
<p class="pc1">Paragraph1</p>
</div>
<div class="c1">Text2
<p class="pc1">Paragraph2</p>
</div>
</div>
这是我正在尝试的脚本:
<script>
$(document).ready(function(){
$("#container").click(function(e){
var a=e.target.children().text();
//I want to store the text in the paragraph (e.g. Paragraph 1, when I click the first div) in var a.
var b=e.target.childNodes[0].nodeValue;
//I want to store the text in the div (e.g. Text1, when I click the first div) in var b.
});
});
</script>
但是它不起作用。我知道我写错了。使用 event.target 属性访问这些文本的正确方法是什么?
最佳答案
e.target
的问题是它可能是 c1
元素或 pc1
元素。
您可以使用 click 事件定位 c1
元素,然后找到 c1
的第一个子元素及其值
$(document).ready(function() {
$("#container").on('click', '.c1', function(e) {
var text = this.firstChild.nodeValue.trim();
snippet.log(text);
});
//using a gloabl handler, they way you have used
$("#container").click(function(e) {
var text = $(e.target).closest('div').contents().first().text();
snippet.log('2: ' + text);
});
});
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div class="c1">Text1
<p class="pc1">Paragraph1</p>
</div>
<div class="c1">Text2
<p class="pc1">Paragraph2</p>
</div>
</div>
关于javascript - 如何使用 event.target 访问特定子项及其文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36637741/