【jquery】结合class选择器、next、prev方法实现相邻的节点展开隐藏效果

在页面效果中,有时候我们程序循环出来的列不能加上ID属性,因为可能有列表可能会循环出多个相同的ID,这样就不能使用Jquery的ID选择器,这时候 我们可以使用Class选择器,

同时我们也可能需求是对此节点元素的操作只局限于当前的div(或table中),我们看代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>jquery效果</title>
    <script src="http://common.cnblogs.com/script/jquery.js" type="text/javascript"></script>
    <script type="text/javascript">
        
//展开隐藏层
        $(document).ready(function () {
            $(
".part").click(function () {
                
var hideP = $(this).next();
                
if (hideP.css('display'== 'none') {
                    hideP.show();
                    $(
this).hide();
                }
                
else {
                    hideP.hide();
                    $(
this).show();
                }
            });
            $(
".all").click(function () {
                
var hideP = $(this).prev();
                
if (hideP.css('display'== 'none') {
                    hideP.show();
                    $(
this).hide();
                }
                
else {
                    hideP.hide();
                    $(
this).show();
                }
            });
        });  
</script>
</head>
<body>
    <!--循环出来的div-->
    <div class='classA'>
        <class="part">内容1</p>
        <class="all" style="display:none">内容1,哈哈哈,我展开了,这里是更多内容哈</p>
    </div>
    <div class='classA'>
        <class="part">内容2</p>
        <class="all" style="display:none">内容2,哈哈哈,我展开了,这里是更多内容哈</p>
    </div>
    <div class='classA'>
        <class="part">内容3</p>
        <class="all" style="display:none">内容3,哈哈哈,我展开了,这里是更多内容哈</p>
    </div>
</body>
</html>

也就是说我想展开 classA处的隐藏内容,同时不影响到其他相同的classA处的内容。其实这里重点也就是jquery next、prev方法的使用,当然还可以用于其他场合。

原文地址:https://www.cnblogs.com/guanjie20/p/2377306.html