If..else 语句基于数组函数结果

If..else statement based off array function results

我想要的是根据数组函数的结果提供不同的 URL。 基本上,如果 collectTags 等于 "church" 或 "concert" 它链接到 A.com 否则它链接到 B.com.

这是我目前拥有的代码:

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);

}

我不确定我是否能做对,但我会试一试。您的问题是您再次访问 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/>');
    }
}