If..else statement based off array function result

2019-09-06 12:19发布

What I want to happen is to have different URLs be provided based of what the array function result is. Basically, if collectTags is equal to "church" or "concert" it links to A.com else it links to B.com.

Here's the code I currently have:

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

}

1条回答
地球回转人心会变
2楼-- · 2019-09-06 12:23

I'm not sure that I can do it right, but I'll give it a try. Your problem is that you access collectTags again. That is an array, not a string, so you comparing it to a string will always be false. And never to use string concatination that will make your code harder to read & mess.

{
    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/>');
    }
}
查看更多
登录 后发表回答