[英]jQuery : toggle class opening all class
我有以下代碼,但遇到了很多問題,但仍然無法運行。
我想使用toggle
但問題是它正在打開與此相關的所有類。我要切換的是僅單擊的類 。
我已經嘗試過e.preventDefault
, e.stopPropagation();
並return false
。但是他們都不為我工作。
注意我不知道上面提到的三個的用法,我在結尾處而不是開頭就使用了它們。
$(".read").click(function(e){ //e.preventDefault(); $(".expand").toggle(); return false; });
.expand{display:none;background:#000;color:white;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <p>Lorem Ipsum Text</p> <div class="read">Read More</div> <div class="expand">Lorem Ipsum text again !</div> <p>Lorem Ipsum Text</p> <div class="read">Read More</div> <div class="expand">Lorem Ipsum text again !</div> <p>Lorem Ipsum Text</p> <div class="read">Read More</div> <div class="expand">Lorem Ipsum text again !</div>
$(".expand")
返回具有類.expand
所有元素的.expand
,但是您只需要獲得一個元素。 你可以這樣
$(".read").click(function(e){
$(this).next('.expand').toggle();
return false;
});
$(".read").click(function(e){ //e.preventDefault(); $(this).next(".expand").toggle(); return false; });
.expand{display:none;background:#000;color:white;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <p>Lorem Ipsum Text</p> <div class="read">Read More</div> <div class="expand">Lorem Ipsum text again !</div> <p>Lorem Ipsum Text</p> <div class="read">Read More</div> <div class="expand">Lorem Ipsum text again !</div> <p>Lorem Ipsum Text</p> <div class="read">Read More</div> <div class="expand">Lorem Ipsum text again !</div>
您可以使用
$(".read").click(function(e){
//e.preventDefault();
$(".read").next(".expand").toggle();
return false;
});
請檢查以下代碼:
$(".read").click(function(e){ //e.preventDefault(); $(this).next('.expand').toggle(); return false; });
.expand{display:none;background:#000;color:white;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <p>Lorem Ipsum Text</p> <div class="read">Read More</div> <div class="expand">Lorem Ipsum text again !</div> <p>Lorem Ipsum Text</p> <div class="read">Read More</div> <div class="expand">Lorem Ipsum text again !</div> <p>Lorem Ipsum Text</p> <div class="read">Read More</div> <div class="expand">Lorem Ipsum text again !</div>
嘗試這樣的事情。 在這里,next()只是獲取下一個元素,而$(this)引用當前單擊的元素。
$(".read").click(function(e){ //e.preventDefault(); $(this).next().toggleClass('expand'); return false; });
.expand{display:none;background:#000;color:white;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <p>Lorem Ipsum Text</p> <div class="read">Read More</div> <div class="expand">Lorem Ipsum text again !</div> <p>Lorem Ipsum Text</p> <div class="read">Read More</div> <div class="expand">Lorem Ipsum text again !</div> <p>Lorem Ipsum Text</p> <div class="read">Read More</div> <div class="expand">Lorem Ipsum text again !</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.