如何在jQuery中使用$(this)访问子元素?
How do I access a sub-element when using $(this) in jQuery
我有以下代码:
$(document).ready(function(){
$(document).on('click', '.mydiv', function(){
console.log(??????);
});
});
我也有相应的html
<div class="mydiv">
<p>Hello from inside a mydiv</p>
</div>
<div class="mydiv">
<p>Hello from inside some other mydiv</p>
</div>
我的目标是在单击mydiv类的任何div时将p标记内的文本打印到控制台中。我知道这意味着我应该使用$(this)操作符,但是当我这样做时,我不确定如何访问它的子元素。
我知道如果我使用id(或者如果我只有一个这些类对象),我可以简单地做$('#mydiv p').val()
,但我不确定如何实现这一点,当我使用$(this)。
您可以使用$('p',this)
或$(this).find('p')
在this
上下文中获取p标记元素:
$(document).on('click', '.mydiv', function(){
console.log($('p',this).text());
});
演示工作使用$(this)
和jQuery的.find()
,你可以得到你选择的子元素:
console.log($(this).find('p').html());
有多种方法可以做到这一点。其他人在这里提到了其中一种方法(find
方法)。find方法的问题是,它查找div中的所有元素,而不是直接的子元素。所以,如果你有嵌套在另一层的元素,它也会得到。
使用children
方法,它将找到元素的直接子元素,但不会找到更深层次的嵌套元素。
<div class="mydiv">
<div>
<p>Nested p</p>
</div>
</div>
$('.mydiv').find('p'); // Finds this element, but children() will not
和
<div class="mydiv">
<p>
Direct p
</p>
</div>
$('.mydiv').children('p'); // Will find this element, but find() will as well
使用find
方法,您将找到嵌套在第二个div中的一个,而使用children
方法,您将只找到直接子元素。
根据您的需要,您可以使用find
或children
相关文章:
- 如何使用(this)访问Angular 2 http rxjs catch函数中的对象属性
- 为什么我不能在 ajax 成功中访问 $(this)
- 在接受功能上访问燃料UX标语牌中的“this”
- $.each 中的“this”,当需要使用“this”访问对象的函数时
- 在jQuery中,我如何从$.ajax回调函数访问$(this)
- TypeScript:在对象文字字段中的访问器中访问外部“this”
- JavaScript 访问函数构造函数中的“this”
- React Native can'无法在render()方法之外访问this.ops
- 通过函数传递“this”时,我是否可以无法访问“this”的属性
- 如何使用“self = this”访问类属性
- 使用“this”访问对象的值
- arguments属性可以由this访问.some_function.arguments?实际上我无法解释
- 使用let初始化的函数在被this访问时不被替换
- 隐藏匿名JavaScript函数中的变量,但使用“this”访问它们
- 如何使用$(this)访问调用Javascript函数的按钮的id
- 在Javascript中无法通过this访问const变量
- 如何在jQuery中使用$(this)访问子元素?
- 无法使用“this”访问对象.“this”指向“窗口”对象
- 使用jQuery的$(this)访问内部文本
- 使用this访问对象内的对象名称