我有一个具有相同类名的div,它在php循环中进行了迭代。只要单击更多链接,所有具有class ='detail-section'的div就会被打开和关闭,而不仅仅是在循环中选择的那个。我试过$(this).closest,它似乎并没有改变任何东西。可能是因为它没有关闭或其他原因。我不知道。任何帮助将不胜感激。
foreach($rows as $a => $b){
<div><a class='more-detail' style='cursor: pointer; font-color:#0000ff;'>More...</a></div>
<div class='detail-section' style='display: none;'>
<!--Content-->
</div>
<div><a class='less-detail' style='cursor: pointer; font-color:#0000ff;'>Less...</a></div>
}
这是我的脚本
<script>
$(document).ready(function(){
$(".more-detail").click(function(){
$(".detail-section").css("display", "block");
$(".more-detail").css("display", "none");
$(".less-detail").css("display", "block");
});
$(".less-detail").click(function(){
$(".detail-section").css("display", "none");
$(".more-detail").css("display", "block");
$(".less-detail").css("display", "none");
});
});
</script>
答案 0 :(得分:3)
将this
与.next()
和.prev()
方法一起使用:
$(".more-detail").click(function(){
$(this).next(".detail-section").css("display", "block");
$(this).next(".less-detail").css("display", "block");
$(this).css("display", "none");
});
$(".less-detail").click(function(){
$(this).prev(".detail-section").css("display", "block");
$(this).prev(".more-detail").css("display", "block");
$(this).css("display", "none");
});
答案 1 :(得分:1)
首先,您必须将html div更改为以下行:
<div>
<a class='more-detail' style='cursor: pointer; font-color:#0000ff;'>More...</a>
<div class='detail-section' style='display: none;'>
details details details details details details details details details details
</div>
<a class='less-detail' style='cursor: pointer; font-color:#0000ff;'>Less...</a>
</div>
然后将您的jquery更改为此:
$(".more-detail").click(function(){
var $this = $(this);
var $detail = $this.next(".detail-section");
var $lessDetail = $detail.next(".less-detail");
$this.css("display", "none");
$detail.css("display", "block");
$lessDetail.css("display", "block");
});
$(".less-detail").click(function(){
var $this = $(this);
var $detail = $this.prev(".detail-section");
var $moreDetails = $detail.prev(".more-detail");
$detail.css("display", "none");
$moreDetails.css("display", "block");
$this.css("display", "none");
});
答案 2 :(得分:0)
尝试使用JavaScript而不是PHP来实现。
document.getElementsByClassName('more-detail').onclick = function(){
document.getElementsByClassName('detail-section').style.display = "block";
document.getElementsByClassName('more-detail').style.display = "none";
document.getElementsByClassName('less-detail').style.display = "block";
}
document.getElementsByClassName('less-detail').onclick = function(){
document.getElementsByClassName('detail-section').style.display = "none";
document.getElementsByClassName('more-detail').style.display = "block";
document.getElementsByClassName('less-detail').style.display = "none";
}