如何使用JQuery中的PREV函数访问SPAN元素?

Mid*_*one 1 html jquery

单击按钮时,需要先查看其发生的特性,然后找到特定的span标记.不幸的是,它要么找不到标签,要么不改变它的内容.

这是不起作用的代码.

$(this).prev("span[id*=CommentText]").hide();
Run Code Online (Sandbox Code Playgroud)

我可以在加载事件期间设置颜色,但是当单击链接时它不会进行任何更改.

这只适用于加载阶段:

$("span[id*=CommentText]").css("background-Color", "red");
Run Code Online (Sandbox Code Playgroud)

编辑:

<html>
<head>
    <script src="../Scripts/jquery-1.3.2-vsdoc.js" type="text/javascript"></script>
    <script src="../Scripts/jquery-1.3.2.js" type="text/javascript"></script>
    <script src="../Scripts/jquery.color.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $("textarea[id*=Comments]").hide().css("background-Color", "white");
            $("span[id*=CommentText]").css("background-Color", "red");
            $("a[id*=CommentLink]").click(LoadComments).css("background-Color", "white");
        });
        function LoadComments() {
            $(this).prev("textarea[id*=Comments]").animate({ backgroundColor: 'yellow' }, 500).show().focus();
            $(this).prev("span[id*=CommentText]").css("background-Color", "white");
            $(this).fadeOut();
        }
    </script>
</head>
<body>
     <span id="Q37CommentText">comments here</span>
     <textarea name="Q37Comments" rows="1" cols="50" id="Q37Comments">comments here</textarea>
     <a id="Q37CommentLink">Add/Edit Comment</a>

     <span id="Q40CommentText">Comment 2</span>
     <textarea name="Q40Comments" rows="1" cols="50" id="Q40Comments">Comment 2</textarea>
     <a id="Q40CommentLink">Add/Edit Comment</a>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

Rus*_*Cam 7

如果你的标记结构总是一样的话,我会倾向于保持它简单并且随意使用

$(this).prev().prev() ...
Run Code Online (Sandbox Code Playgroud)

其他替代品正​​在使用 prevAll()

$(this).prevAll('span:first'); // may or may not need the attribute filter depending
                            // on if there are more <span> elements as siblings
Run Code Online (Sandbox Code Playgroud)

导航到父级然后调用 find()

$(this).parent().find('span[id*=CommentText]');
Run Code Online (Sandbox Code Playgroud)

附注:

只看你的标记,使用CSS类可能更容易,而不是ids和属性过滤器来选择基于以开头,结尾或包含的ID的元素x.这可能是在所有快/几乎所有的浏览器(尤其是那些执行document.getElementsByClassName(classNames)选择器API)