开发者

jQuery: get previous tag, nesting problem

I'm trying to get the previous tag from $('#marker').prevAll("span.curPos:eq(1)");

Problem is that the HTML might look like:

<span class="curPos">some text</span><em><span class="curPos">more</span></em>
<div id="marker">bla</div>
<span class="curPos">... text</span>

And all methods I've tried in order to get the previous span element with class="curPos" seems to ignore the span-tag if it's inside some other tag, like em.

It will simply ignore everything in the nested EM tag and instead return the previous curPos before the EM.

Any idea how I can get the previous tag even if it's nested 1-n levels ?

-- edit:

all of this is wrapped in a container DIV, I would also prefer if it never looked outside this div - not reversing back any further than to that div/selector.

maybe there's a way to extract all HTML from between 2 selectors? if so, I could solve it with regex and insert back?

script in action: http://jsfiddle.net/H6fvy/ (used to key track 开发者_JAVA技巧of "cursor")


Yeah, prevAll() only checks the siblings so that makes sense that anything nested isn't matched.

Is it possible to embed the <em> within the <span> instead of the other way around? This seems to me like a case where it might be better to alter the markup to more cleanly work with your scripts instead of trying to force the jQuery.

EDIT: Ok, so changing the markup won't work, that's fine. This is an interesting little problem actually. Here's a solution that will work, but I still can't help think that there's a better approach out there.

Given your initial markup of

<span class="curPos">some text</span>
<em><span class="curPos">more</span></em>
<div id="marker">bla</div>

This script will select the closet previous element, regardless of nesting

<script type="text/javascript">
    $(function () {
        $('#marker').prevAll().each(function () {
            console.log('Looping...');

            var $this = $(this);
            var matchedText;

            if ($this.hasClass('curPos')) {
                matchedText = $this.text();
            }
            else {
                var nested = $this.find('.curPos');
                if (nested)
                    matchedText = nested.text();
            }

            if (matchedText) {
                console.log(matchedText);
                return false;
            }
        });
    });
</script>

I've got some logging in there just to indicate that it does what it's supposed to. It loops through all previous elements using each(), but bails on the loop as soon as it finds a match by using return false; Hopefully this can be modified to suit your needs. Best of luck.


This worked fine:

$('#marker').prev().css("background", "yellow")

see http://jsfiddle.net/U2ryA/


Try the selector

Span[class=curPos]

That should select all spans with that class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜