2014-10-02 30 views
1

所以,我現在使用blogger.com作爲我的博客平臺。我們知道,博主是一個非常簡單的平臺,不支持任何高級編程語言。只能用Javascript做任何詭計。javascript - 檢測文章標籤內容自動分配文章類

我的文章是關於個人博客與WordPress的使用一些職位格式,我有一個標準的職位,音頻文章和視頻文章。我想根據我的帖子格式類型在帖子標題旁顯示帖子格式圖標。視頻後期將有視頻圖標的標題旁,音頻後期將有音頻圖標的標題旁,等...

這是我的帖子標記:

<div class="post"> 
    <h3> 
     <a href="#">Post title</a> 
    </h3> 
    <!--content goes here--> 
</div> 

在JavaScript中可以找出我的帖子格式,我將添加一個標籤我的帖子裏這樣的:<span data-format="audio-format"></span><span data-format="video-format"></span>,等...

<div class="post"> 
    <h3> 
     <a href="#">Post title</a> 
    </h3> 
    <span data-format="video-format"></span> 
    <!--content goes here--> 
</div> 

然後JavaScript的一個類添加到我的帖子的標記,這樣我就可以設置基於CSS類招的圖標。例如,如果我的文章格式是音頻(<span data-format="audio-format"></span>),則Javascript會將audio-format「CSS class」添加到我的帖子標記中。

<div class="post audio-format"> 
    <h3> 
     <a href="#">Post title</a> 
    </h3> 
    <span data-format="audio-format"></span> 
    <!--content goes here--> 
</div> 

不幸的是,我的技能只是HTML和CSS,我不精通Javascript或jQuery的。 Javascript技巧有可能嗎? PS:對不起,我的英文不好。

回答

2

如果我理解正確的問題:

$('div.post').has('span[data-format]').addClass(function() { 
    var format = $('span[data-format]', this).data('format'); 
    return 'post-format-' + format.split('-')[0]; 
}); 

一種替代方案:

[].slice.call(document.querySelectorAll('.post')).forEach(function(post) { 
    var span = post.querySelector('span[data-format]'); 
    if (!span) return; 
    var format = span.getAttribute('data-format').split('-')[0]; 
    post.classList.add('post-format-' + format); 
}); 

編輯:根據改變的標記,你應該只是取消拆分部分。

$('div.post').addClass(function() { 
    return $('span[data-format]', this).data('format'); 
}); 
+0

它實際上會導致_post-audio-post_而不是_post-format-audio_。但我的答案有點長,所以我希望你能修好你的答案。 – Regent 2014-10-02 06:22:32

+0

@Regent是的,那就是當你不測試你的代碼時會發生什麼,謝謝! – undefined 2014-10-02 06:29:04

+0

不客氣。未經測試,您的測試速度超過我的測試速度:)現在是正確的,+1。 – Regent 2014-10-02 06:32:55