仅定位页面上的一个元素

时间:2014-07-20 06:01:14

标签: javascript jquery tumblr

我写JS或jQuery已经有一段时间了,现在我遇到了这个新手问题。我试图定位一个文本所在的元素,而不是页面上具有相同类的所有元素。

我试图将用户在照片标题中的第一个粗线放入其他元素中。此代码有效,但我需要确保它不相同。就像用户有2张照片而其他人有标题一样,它应该像在此代码中一样重复。

Heres:我的HTML(使用Tumblr助手):

{block:Photoset}
                    <div class="photoset-grid" data-layout="{PhotosetLayout}">
                        <div class="photoset-posts">
                            <div class="wrap">
                                {block:Photos}<img src="{PhotoURL-HighRes}"/>     {/block:Photos}
                            </div>
                            <div class="background-wrap"></div>
                        </div>
                        <a class="post-date" href="{Permalink}">{TimeAgo}</a>
                        {block:Caption}<div class="caption">{Caption}</div>{/block:Caption}
                        <div class="post-details">
                            {block:HasTags}
                            <div class="post-details-tags">
                                {block:Tags}<a href="{TagURL}">#{Tag}</a>{/block:Tags}
                            </div>
                            {/block:HasTags}
                            <div class="post-details-buttons">
                                <i>{LikeButton}</i>
                                <i>{ReblogButton}</i>
                            </div>
                        </div>
                    </div>
                    {/block:Photoset}

继承我的JS:

// variables
var $photoCaption = $(".photo .wrap .caption strong:first-child").text();
var $removableElement = $(".photo .wrap .caption strong:first-child");

// remove original element
$(".photo .caption strong:first-child").parent().remove();
$removableElement.remove();

// place new element to its place
$(".photo .photo-photo").append("<p class='photo-caption'>" + $photoCaption + "</p>");

谢谢,所有。

1 个答案:

答案 0 :(得分:2)

您在回复jfriend时发布的jsFiddle有助于澄清您的意思。

我想我会尝试以下内容:

$(".photo .caption").each(function() {
    var $strongChildren = $(this).children('strong');
    if ($strongChildren.length > 0) { 
        var $removableElement = $(".photo .caption").children('strong').first();
        var $photoCaption = $removableElement.text();

        // remove original element
        $removableElement.remove();

        // place new element to its place
        $(this).siblings(".photo-photo").append("<p class='photo-caption'>" + $photoCaption + "</p>");
    }
});

还有其他方法可以做到。例如,您还可以找到所有首子字符串,然后调用$removableElement.closest('.photo');以仅获取其包含.photo元素。

但上面的代码应该可行。如果您有任何问题,请告诉我。

相关问题