2017-03-08 45 views
0

我想要發生的是根據數組函數的結果提供不同的URL。 基本上,如果collectTags等於「教堂」或「音樂會」,則鏈接到A.com,否則鏈接到B.com。If..else基於數組函數結果的語句

這是我目前擁有的代碼:

caption : function(instance, item) { 
    var caption, link, collectTags, tags; 

    caption = $(this).data('caption'); 
    link = '<a href="' + item.src + '">Download image</a>'; 
    collectTags = $(this).parent().attr("class").split(' '); 
    tags = $.map(collectTags,function(it){ if(collectTags === "church"){ return '<a href="A.com' + it + '">'+ it +'</a>'} else{return '<a href="B.com' + it + '">'+ it +'</a>'};}); 

    return (caption ? caption + '<br />' : '') + link + '<br/>' + tags.slice(1); 

} 
+0

代碼有什麼問題? –

+0

你還在嗎? –

回答

2

我不知道,我可以這樣做的權利,但我會試試看。你的問題是你再次訪問collectTags。這是一個數組,而不是一個字符串,所以您將它與一個字符串進行比較始終是錯誤的。永遠不要使用字符串連接,這會使你的代碼更難以閱讀&混亂。

{ 
    caption: function (instance, item) { 
     var caption, link, collectTags, tags; 

     function format(tpl, binding) { 
      if (typeof binding != 'function') return format(tpl, function (_, name) { 
       return binding[name]; 
      }); 
      return tpl.replace(/\$(\w+)/g, binding); 
     } 

     caption = $(this).data('caption'); 
     link = format('<a href="$src">Download image</a>', item); 
     collectTags = $(this).parent().attr("class").split(' '); 
     function createTag(it) { 
      return format("<a href='$site/$it'>$it</a>", { 
       site: (it == 'church' || it == 'concert') ? 'A.com' : 'B.com', 
       it: it 
      }); 

     } 

     tags = $.map(collectTags, createTag); 
     return [].concat(caption ? [caption, link] : link).concat(tags).join('<br/>'); 
    } 
} 
+0

這似乎已經成功了。我想我可以擴展這一點 – Capwiz