到目前为止,我已经编写了这段代码 -
<div class="yearly-archive">
<p> YEAR - <span class="archive-year year-active"> 2014 </span> /
<span class="archive-year"> 2013 </span> /
<span class="archive-year"> 2012 </span> /
<span class="archive-year"> 2011 </span> /
<span class="archive-year"> 2010 </span>
</p>
</div>
<div class="news-container news-active" id="news-2014"></div>
<div class="news-container" id="news-2013"></div>
<div class="news-container" id="news-2012"></div>
<div class="news-container" id="news-2011"></div>
<script>
$('.archive-year').click(function() {
$('.archive-year').removeClass('year-active');
$(this).addClass('year-active');
});
</script>
小提琴:http://jsfiddle.net/codestor/C7xj6/2/
我正在尝试实现以下功能:
当我点击2013时,新闻容器的新闻活动应切换为ID为 news-2013
需要帮助。
答案 0 :(得分:1)
您希望对链接执行几乎相同的操作...从单击的链接中获取文本并使用它来构建您的ID选择器。由于您点击了哪个链接,因此您想要使用$(this).text()
抓取链接中的文字,那么您需要确保使用.trim()
删除文本周围的任何额外空格。现在,您可以通过将字符串与'#news-1' + <link text value>
Try ...
$('.archive-year').click(function() {
$('.archive-year').removeClass('year-active');
$(this).addClass('year-active');
$(".news-container").removeClass("news-active");
$("#news-" + $(this).text().trim()).addClass("news-active");
});
答案 1 :(得分:1)
使用$(this).text()
读取点击的范围文本,然后将类添加到其相对div中,如下所示:
$('.archive-year').click(function(e) {
e.preventDefault();
$('.archive-year').removeClass('year-active'); // remove class from all span
$(this).addClass('year-active'); //add to current clicked
$(".news-container").removeClass("news-active"); // remove class from all div
$('#news-'+$.trim($(this).text())).addClass("news-active"); // add to current relative div
});
所有技巧都在这里:$('#news-'+$.trim($(this).text())).addClass("news-active");
阅读范围文本,修剪它并连接id 新闻 - 部分并添加news-active
类。
答案 2 :(得分:0)
$(document).on('click', function(event){
if($(event.target).hasClass('archive-year') && $(event.target).text() == ' 2013 '){
$(div[class='news-container news-active']).attr('id', 'news-2013');
}
})
答案 3 :(得分:0)
你可以试试这个:
$(function(){
$('.archive-year').click(function() {
$('.year-active').removeClass('year-active');
$('.news-active').removeClass('news-active');
$(this).addClass('year-active');
$('.news-container[id*="'+ $.trim(this.textContent) +'"]').addClass('news-active');
});
});