简体   繁体   中英

Get a string in a variable to create a dynamic link in Javascript

What I am trying to accomplish is to have a map that has a few locations. Whenever users click on each location, a popup will emerge with some information. I am trying to create a dynamic link inside that popup.

Below is my code in Javascript

function parseDescription(message){
    var string=""

    for(var i in message){
        if (i=="CommunityPartner"){
            string+='<span style="font-weight:bold">'+i+'</span>'+": "+message[i]+'</a>'+"<br>"
        } else if (i=="WeitzCECPartner"){
            string+='<span style="font-weight:bold">'+i+'</span>'+": "+message[i]+'</a>'+"<br>"
        } else if (i=="PhoneNumber"){
            string+='<span style="font-weight:bold">'+i+'</span>'+": "+message[i]+'</a>'+"<br>"
        } else if (i=="Website"){
            var link = "http://www."+message[i];
            string+='<span style="font-weight:bold">'+i+'</span>'+": "+'<a href="{{link}}" >'+link+'</a>'+"<br>"
        }
        //string+='<span style="font-weight:bold">'+i+'</span>'+": "+message[i]+"<br>"
    }
    return string;
}

在此输入图像描述

I keep getting this error. I think it's related to the value passed into "a href" :

Request Method: GET
Request URL:    http://127.0.0.1:8000/%7B%7Blink%7D%7D

Please help

Instead of using {{link}} in the string, you can try this:

var link = "http://www." + message[i];
string += '<span style="font-weight:bold">' + i + '</span>: <a href="' + link + '">' + link + '</a><br>';

The following syntax:

{{link}}

is incorrect, because this part was inside a string it was interpreted by the JS engine as a string.

You can use template strings (backticks `) to insert variables as string into another string. For example:

`<span style="font-weight:bold">${i}</span>:<a href="${link}" >${link}</a><br>`;

This example assumes that link and i are both variables which you want to insert dynamically into your string. If you have more questions leave a comment.

I think the problem lies in the {{link}}. Your code looks like native js and not angular or any other framework. Thus, the characters {{}} inside a string do not mean anything. The url that you get is exactly those characters, escaped. Use plain old string concatination to enter your href value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM