提问人:dtd439 提问时间:4/4/2023 更新时间:4/4/2023 访问量:29
有没有办法多次使用关键字(this)
is there a way to use the keyword (this) more than once
问:
jquery:
$(document).ready(function() {
$(".title", this).click(function(){
$(".content", this).slideToggle();
});
});
代码看起来不错,但它不起作用。请帮忙。谢谢
答:
0赞
Martin Lisowski
4/4/2023
#1
提供 HTML 显示了问题:
您的 DIV 不是 so 返回和 emtpy jQuery 对象的子对象。如果您不想重新排列 HTML,我建议使用该函数:https://api.jquery.com/siblings/#siblings-selectorcontent
title
$(".content", this)
siblings()
$(document).ready(function() {
$(".title", this).click(function() {
console.log(this.tagName+" "+this.innerHTML);
$(this).siblings(".content").slideToggle();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="title">im a title</div>
<div class="content">this is a text</div>
</div>
<div class="container">
<div class="title">im another title</div>
<div class="content">and another text</div>
</div>
评论
.title
.content
.slideToggle()
<div class="container"> <div class="title">im a title</div> <div class="content">this is a text</div> </div> <div class="container"> <div class="title">im another title</div> <div class="content">and another text</div> </div>
.content
.title
$(this).next().slideToggle();
document >> .title >> .content
document >> .title + .container
this
$(".title")