If..else statement based off array function results

和自甴很熟 提交于 2019-12-25 09:28:26

问题


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:


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/>');
    }
}


来源:https://stackoverflow.com/questions/42678998/if-else-statement-based-off-array-function-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!