javascript $(this) div 中标题的 jQuery 选择器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16017464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery selector for a heading in $(this) div
提问by Taimur
I need to select and find the html value of the H2 tag within a particular div which is clicked, this is what I'm trying right now but to no avail:
我需要在单击的特定 div 中选择并找到 H2 标签的 html 值,这就是我现在正在尝试但无济于事:
When the .square is clicked, I'm trying to run this:
当 .square 被点击时,我试图运行这个:
$(this).find('h2').html();
and this is what the html looks like:
这就是 html 的样子:
<div class="square" id="2"><h2>Title</h2><h3>Comment</h3></div>
What am I doing wrong?
我究竟做错了什么?
Thanks
谢谢
回答by Ja?ck
Your code has to be placed inside a click handler like so:
您的代码必须放置在点击处理程序中,如下所示:
$('.square').on('click', function() {
alert($(this).find('h2').html());
}
Outside of the click handler, this
points to window
and $(window).find('h2')
doesn't find anything and thus .html()
yields undefined
.
单击处理之外,this
分window
而$(window).find('h2')
没有找到任何东西,因此.html()
收益率undefined
。
If your <div class="square">
is dynamically generated, you need to "hook" your click handler onto the closest element that will not disappear from the page.
如果您<div class="square">
是动态生成的,则需要将单击处理程序“挂钩”到不会从页面中消失的最近元素上。
$('#element_id').on('click', '.square', function() {
alert($(this).find('h2').html());
}
回答by borisrorsvort
A more efficient way for doing this is:
一种更有效的方法是:
$('body').on('click', '.square', function(event) {
var html = $(this).find('h2').html();
console.log(html);
});
回答by Bruno
Maybe you have to run the code after the document is ready.
也许您必须在文档准备好后运行代码。
$(function() {
$(".square").click(function() {
console.log($(this).find('h2').html());
});
});
$(function() {});
is the short way to write $(document).ready(funciton() {});
.
$(function() {});
是写的简短方法$(document).ready(funciton() {});
。
Moreover your code has to be placed as callback of the click event listener.
此外,您的代码必须作为点击事件侦听器的回调放置。
回答by Filipe Fonseca
Your code is entirely correct. You may see an example of an application here (or on the 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>