【问题标题】:Multiple use of backticks within Javascript在 Javascript 中多次使用反引号
【发布时间】:2021-09-16 16:55:52
【问题描述】:

我在使用反引号时遇到了一些问题,我想知道是否有人可以帮助我。我有下面的代码,它允许我输出多个响应。问题是,当我在 target="_blank">here` 后面加上逗号时,它不允许我添加更多短语。我曾尝试在反引号之前使用退格键来突破它,但没有运气。这是我的代码,我使用的是 Javascript 和 HTML。

<script>
function talk(){
var know ={
        "How does this work":"I can help you find what you're looking for.",
        "how does this work":"I can help you find what you're looking for.",        

        "contact":`You can contact us by clicking <a href='https://addressname.com' target="_blank">here</a>` 
};  

var user = document.getElementById('userBox').value;
document.getElementById('chatLog').innerHTML = user + "<br>";
if(user in know){
    document.getElementById('chatLog').innerHTML = know[user] + "<br>";
}else{
    document.getElementById('chatLog').innerHTML = "I do not understand.";
}
}

</script>

为了澄清,我需要这样的东西:(但显然逗号不起作用)

"How does this work":"I can help you find what you're looking for.",
        "how does this work":"I can help you find what you're looking for.",        

        "contact":`You can contact us by clicking <a href='https://addressname.com'target="_blank">here</a>`,
        "help":`You can find help by clicking <a href='https://addressname.com'target="_blank">here</a>`

【问题讨论】:

  • 这对我有用:jsfiddle.net/jfhxey65。你遇到了什么错误?
  • @BankBuilder 太奇怪了,它现在对我来说很完美。谢谢!也许我最初在某个地方使用了撇号而不是反引号。

标签: javascript html template-literals backticks


【解决方案1】:

如您所知,"' 的使用应该相互对应

属性值的双引号在 HTML 中最常见,但也可以使用单引号。
在某些情况下,当属性值本身包含双引号时,需要使用单引号:

&lt;p title='John "ShotGun" Nelson'&gt;

反之亦然:

&lt;p title="John 'ShotGun' Nelson"&gt;

反斜杠 (\) 转义字符将特殊字符转换为字符串字符。
如果中间有额外的符号,您可以在它们之前使用\ 反斜杠,这样它们就不会干扰代码并被视为这样的符号:

&lt;p title="John \'ShotGun\' Nelson you\'re a good\\bad person"&gt;
它将像这样显示:
John 'ShotGun' Nelson 你是个好\坏人

Refer to this for more about backslash

【讨论】:

    猜你喜欢
    • 2015-02-25
    • 2014-06-14
    • 2021-10-07
    • 2017-03-27
    • 2014-09-28
    • 2017-07-18
    • 2017-12-07
    相关资源
    最近更新 更多