[英]How to include a condition inside a string using Javascript
I know for singular results, I can do something like this:我知道对于奇异的结果,我可以做这样的事情:
return "this is a condition test within a string - " + {0:'⚪',1:'🟡',2:'🔴',3:'🟢',8:'',9:''}[event.FlagInd.toString()]
where 0
, 1
, 2
etc are values from the variable event.FlagInd
, and the results are the values inside the quoted strings such as '⚪'
其中0
、 1
、 2
等是变量event.FlagInd
的值,结果是带引号的字符串中的值,例如'⚪'
etc ETC
So in the example above, a value of 1 in the event.FlagID
, replaces the 1 with - a yellow ball因此,在上面的示例中, event.FlagID
中的值为 1,将 1 替换为 - 一个黄色球
I am trying to do something similar, to "turn on or off" actual HTML inside a string.我正在尝试做类似的事情,以“打开或关闭”字符串中的实际 HTML。
My current attempts return invalid strings or the strings are not formed correctly.我当前的尝试返回无效字符串或字符串格式不正确。
return
"<strong style=\"font-size:18px;\">" +
{
0: '', default: "<a href=\" + "https://www.marinetraffic.com/en/ais/details/ships/imo:" + event.imo +
"/vessel:" + event.text + "\" target=\"_blank\">" + event.text + "</a>"' }[event.imo.toString()] +
"</strong>" + ... etc
What I am trying to do is return an empty string if the value of event.IMO = 0
, but to return this entire html string, if the value is something other than 0...我想做的是,如果event.IMO = 0
的值返回一个空字符串,但返回整个 html 字符串,如果该值不是 0...
"<a href=\"https://www.marinetraffic.com/en/ais/details/ships/imo:" + event.imo + "/vessel:" + event.text + "\" target=\"_blank\">" + event.text + "</a>"
Thanks to @Ouroborus, I was able to do it... as per this example:感谢@Ouroborus,我能够做到......按照这个例子:
function myResult(IMO, text){
return "Answer is " +
(IMO.toString() == 0 ? "nothing here" :
"<strong style=\"font-size:18px;\">" +
"<a href=\"https://www.marinetraffic.com/en/ais/details/ships/imo:" + IMO +
"/vessel:" + text + "\" target=\"_blank\">" + text + "</a>" +
"</strong>")
}
document.write(myResult("0123","myShip"))
Changing the value from "0123" to "0" gives me the "nothing here", otherwise it's the HTML entirely.将值从“0123”更改为“0”给我“这里什么都没有”,否则它完全是 HTML。 Just got to make sure you format the HTML as a string correctly.只需确保将 HTML 正确格式化为字符串即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.