查找数据属性和兄弟div信息



我有一篇博客文章,我正试图添加下一篇文章和上一篇文章的功能。我使用JS来做到这一点。

我从一个HTML页面中提取数据,该页面列出了所有带有HTML的博客文章,如下所示:

<div class="post-info" data-blog-post-ID="472140">
 <span class="link">/blog/post4</span> <!-- URL OF BLOG POST -->
 <span class="title">Post  4</span> <!-- TITLE OF BLOG POST -->
</div>

一旦我拉入数据,我想运行一个函数,将比较当前帖子的博客ID,然后在数据中找到它。这样做之后,我想找到包含博客ID的div的前一个和下一个兄弟,并使用.html将其插入页面。

我试着让这个工作,但它没有。没有错误,所以我相信我的JS是错误地选择元素?

这是我尝试的:

$(function() {
    var blogID = "{tag_blogpostid}",
        blogList = $(".blog-post-list").find("[data-blog-post-ID='" + blogID + "']");
    if (blogID == blogList){
        var prevLink = $(blogList).prev( ".link" ).text(),
            prevTitle = $(blogList).prev( ".title" ).text(),
            nextLink = $(blogList).next( ".link" ).text(),
            nextTitle = $(blogList).next( ".title" ).text();
        $( ".prev" ).html( '<a href="' + prevLink + '">' +prevTitle+ '</a>' );
        $( ".next" ).html( '<a href="' + nextLink + '">' +nextTitle+ '</a>' );
    }
});

这是一个jsFiddle与额外的HTML和上述代码。

问题是什么,我如何解决问题,这样我就可以创造我想要实现的目标。

让我们看一下代码:

var blogID = "{tag_blogpostid}",
    blogList = $(".blog-post-list").find("[data-blog-post-ID='" + blogID + "']");
if (blogID == blogList){

你在比较什么?

blogID    <-- String
blogList  <-- jQuery object

一个字符串永远不会等于一个jQuery对象。

你应该检查长度

if (blogList.length) {
    ...
}

blogList是一个jQuery对象,所以没有必要继续包装它在$()blogList.find(...)就可以了。

,最后prev是错误的,它正在寻找具有类链接的兄弟节点。链接类是该兄弟类的子类。

prevLink = blogList.prev(".post-info").find( ".link" ).text()

你当然要对别人这么做。


$(function() {
    var blogID = "472140",
        blogList = $(".blog-post-list").find("[data-blog-post-ID='" + blogID + "']");
    if (blogList.length){
        var prev = blogList.prev(".post-info"),
            next =  blogList.next(".post-info"),
            prevLink = prev.find( ".link" ).text(),
            prevTitle = prev.find( ".title" ).text(),
            nextLink = next.find( ".link" ).text(),
            nextTitle = next.find( ".title" ).text();
        $( ".prev" ).html( '<a href="' + prevLink + '">' +prevTitle+ '</a>' );
        $( ".next" ).html( '<a href="' + nextLink + '">' +nextTitle+ '</a>' );
    }
});

修改:http://jsfiddle.net/3XjUx/

这是一个工作的演示

$(function() {
  var blogID = "472140",
      blogList = $(".blog-post-list").find("[data-blog-post-ID='" + blogID + "']");
  if (blogList.length){ 
    var prevLink = blogList.prev().find(".link" ).text(),
        prevTitle = blogList.prev().find( ".title" ).text(),
        nextLink = blogList.next().find( ".link" ).text(),
        nextTitle = blogList.next().find( ".title" ).text();
    $( ".prev" ).html( '<a href="' + prevLink + '">' +prevTitle+ '</a>' );
    $( ".next" ).html( '<a href="' + nextLink + '">' +nextTitle+ '</a>' );
  }
});

正如epascarello所说,bloglist是一个jQuery对象,所以没有必要继续在$()中包装它。另外,由于blogList捕获了一个div,因此我更改了previous和next的迭代,但您可以随意更改,只需注意blogList代表的内容。

EDIT又一次,epascarello抢在我前面…但是,检查blogList上的长度以确保找到div会更简洁。

最新更新