如何将data-index属性传递给photoswipe js的索引?

时间:2016-06-11 04:23:00

标签: javascript jquery photoswipe

参考照片ws:http://photoswipe.com/documentation/getting-started.html

我无法将data-index属性传递给photoswipe的索引。

HTML:

    <td>
        <div class="picture" itemscope="" itemtype="http://schema.org/ImageGallery">
            <figure style="display:initial;" itemprop="associatedMedia" itemscope="" itemtype="http://schema.org/ImageObject">
                <a class="picture" href="images/AN241_02.jpg" itemprop="contentUrl" data-size="2000x1200" data-index="0" data-title="AN241 02 55">
                    <img class="lazy thumbnail " data-original="image_cache/AN241_02-cache.jpg" itemprop="thumbnail" alt="Image description" src="image_cache/AN241_02-cache.jpg" style="display: inline;">
                </a>
            <figcaption itemprop="caption description">description</figcaption>
            </figure>
        </div>
    </td>

JS:

var onThumbnailsClick = function(e) {
    e = e || window.event;
    e.preventDefault ? e.preventDefault() : e.returnValue = false;

    var eTarget = e.target || e.srcElement;

    // find root element of slide
    var clickedListItem = closest(eTarget, function(el) {
        return (el.tagName && el.tagName.toUpperCase() === 'FIGURE');
    });

    });

    if(!clickedListItem) {
        return;
    }

    // find index of clicked item by looping through all child nodes
    // alternatively, you may define index via data- attribute <---HOW?

    var clickedGallery = clickedListItem.parentNode,
        childNodes = clickedListItem.parentNode.childNodes,
        numChildNodes = childNodes.length,
        nodeIndex = 0,
        index;

    for (var i = 0; i < numChildNodes; i++) {
        if(childNodes[i].nodeType !== 1) { 
            continue; 
        }

        if(childNodes[i] === clickedListItem) {
            index = nodeIndex;
            break;
        }
        nodeIndex++;
    }


    if(index >= 0) {
        // open PhotoSwipe if valid index found
        openPhotoSwipe( index, clickedGallery );
    }
    return false;
};

你可以在上面看到&#34;数据索引&#34;属性位于&#34; a&#34;我希望将这个传递给JS中的索引。

道歉,因为我不熟悉JS,并希望在此提供任何帮助。

1 个答案:

答案 0 :(得分:0)

如果你需要获取数据索引,你必须在最后一个“If”语句之前从你点击的元素中获取这个属性的值,然后将它传递给openPhotoSwipe init函数:)

var newIndex = parseInt(eTarget.parentNode.getAttribute("data-index"));

if(newIndex >= 0) {
    // open PhotoSwipe if valid index found
    openPhotoSwipe( newIndex, clickedGallery );
}