我有一个情况,需要在自定义CMS中浏览博客文章列表。每篇博客文章都包含在<li>
标签中,页面上有多篇文章。我有一段代码可以在每篇博客文章中添加ShareThis按钮集。不幸的是,所有博客文章的类名都以“post”开头。例如:
<div class="blogList">
<ul>
<li class="post1">
<h2 class="postTitle">A Sample Title</h2>
<div class="postDescription">Some sample content</div>
</li>
<li class="post2">
<h2 class="postTitle">A Sample Title</h2>
<div class="postDescription">Some sample content</div>
</li>
</ul>
</div>
我曾经使用 ".each" 在 li 上进行排序,但这样会将其添加到任何帖子内容中包含的列表中。因此,我只想将其添加一次到每个博客文章的实际父 li 中。
我的目标是仅将其添加到 class 为 "post" 和数字的 <li>
中。我不能只查找 post,因为它也会将其添加到任何其他以 "post" 开头的类别中。
如何仅选择仅具有 "post" 和数字类别的元素?因此,在上面的示例中,我只想查找 li.post1、li.post2 等元素。所有其他元素都将被跳过。
我正在使用 jquery 进行此操作,感觉接近成功,但似乎无法克服这个障碍。
以下是我完整使用的代码示例。
<script type="text/javascript">
$(document).ready(function(){
//Run through the page and find each individual blog post
$('.blogList li [class^="post"]').each(function () {
//Grab post title & encode any quotes so they don't mess up generated HTML
var postTitle = $.trim($(this).children(".postTitle").text().replace('"g, "'));
//Grab URL from the anchor element inside the h2 element (will not grab correct link in admin mode)
var postLink = location.protocol + '//' + location.host + $(this).children("h2").find("a[href]").attr('href');
//Add "share this" HTML elements to the bottom of the post
$(this).append(
'<div class="st">' +
'<span class="st_twitter" displayText="Tweet" st_url="' + postLink + '" st_title="' + postTitle + '"></span>' +
'<span class="st_facebook" displayText="Facebook" st_url="' + postLink + '" st_title="' + postTitle + '"></span>' +
'<span class="st_linkedin" displayText="LinkedIn" st_url="' + postLink + '" st_title="' + postTitle + '"></span>' +
'<span class="st_email" displayText="Email" st_url="' + postLink + '" st_title="' + postTitle + '"></span>' +
'<span class="st_blogger" displayText="Blogger" st_url="' + postLink + '" st_title="' + postTitle + '"></span>' +
'<span class="st_sharethis" displayText="ShareThis" st_url="' + postLink + '" st_title="' + postTitle + '"></span>' +
'</div>'
);
});
});
</script>