我需要在单击的特定 div 中选择并找到 H2 标记的 html 值,这是我现在正在尝试的,但无济于事:
单击 .square 时,我正在尝试运行:
$(this).find('h2').html();
这就是 html 的样子:
<div class="square" id="2"><h2>Title</h2><h3>Comment</h3></div>
我究竟做错了什么?
谢谢
我需要在单击的特定 div 中选择并找到 H2 标记的 html 值,这是我现在正在尝试的,但无济于事:
单击 .square 时,我正在尝试运行:
$(this).find('h2').html();
这就是 html 的样子:
<div class="square" id="2"><h2>Title</h2><h3>Comment</h3></div>
我究竟做错了什么?
谢谢
您的代码必须放置在点击处理程序中,如下所示:
$('.square').on('click', function() {
alert($(this).find('h2').html());
}
在点击处理程序之外,this
指向window
并$(window).find('h2')
没有找到任何东西,因此会.html()
产生undefined
。
如果您<div class="square">
是动态生成的,则需要将您的点击处理程序“挂钩”到不会从页面中消失的最接近的元素上。
$('#element_id').on('click', '.square', function() {
alert($(this).find('h2').html());
}
也许您必须在文档准备好后运行代码。
$(function() {
$(".square").click(function() {
console.log($(this).find('h2').html());
});
});
$(function() {});
是写的简短方法$(document).ready(funciton() {});
。
此外,您的代码必须作为点击事件侦听器的回调放置。
一种更有效的方法是:
$('body').on('click', '.square', function(event) {
var html = $(this).find('h2').html();
console.log(html);
});
您的代码完全正确。您可能会在此处(或在fiddle上)看到一个应用程序示例:
<script>
$(document).ready(function(){
$("div#2").click(function(){
var title = $(this).find('h2').html();
$("span").text(title);
});
});
</script>
<div class="square" id="1"><h2>I'll not work because my id is 1</h2></div>
<div class="square" id="2"><h2>Click me and you'll see me below on the span!</h2></div>
<span></span>