简体   繁体   English

JavaScript 向 href 添加变量

[英]JavaScript adding variable to href

I have a json that is taking from a db information and showing as link, im trying to show the link from db but im gettig some issues, this is what i have:我有一个从 db 信息中获取并显示为链接的 json,我试图显示来自 db 的链接,但我遇到了一些问题,这就是我所拥有的:

 $("#content_div").html('<a href="'.knowledge_info.'"><h4 class="knowledge_base">Knowledge Info</h4></a>');

When doing this im getting :这样做时,我得到:

Uncaught SyntaxError: Unexpected string

Not sure why, the variable is there, when doing console.log(knowledge_info);不知道为什么,变量在那里,当做 console.log(knowledge_info); i can see the info coming from the variable我可以看到来自变量的信息

JavaScript string concatenation is with the + sign: JavaScript 字符串连接使用+符号:

$("#content_div").html('<a href="'+knowledge_info+'"><h4 class="knowledge_base">Knowledge Info</h4></a>');

If your IDE doesn't show you this is syntactically wrong you should probably find another editor and check out some JS basics courses.如果您的 IDE 没有向您显示这是语法错误,您可能应该找到另一个编辑器并查看一些 JS 基础课程。

您可以连接字符串而不是使用点吗?

 $("#content_div").html('<a href="'+knowledge_info+'"><h4 class="knowledge_base">Knowledge Info</h4></a>');

if you use ES6 you can type like this如果你使用 ES6 你可以这样输入

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="content_div"> run snippet </div> <script> const knowledge_info = "href://yourlink" $("#content_div").html(` <a href="${knowledge_info}"> <h4 class="knowledge_base">Knowledge Info</h4> </a> `); </script>

and in js must be camelCase variables "knowledge_info"=>"knowledgeInfo"并且在js中必须是camelCase变量“knowledge_info”=>“knowledgeInfo”

. operator is invalid in javascript.运算符在 javascript 中无效。

It is used in php to combine string.它在php用于组合字符串。

So you would replace .所以你会替换. operator to + .运算符到+

$("#content_div").html('<a href="'+knowledge_info+'"><h4 class="knowledge_base">Knowledge Info</h4></a>');

You could try using template strings like so:您可以尝试使用这样的模板字符串

 $("#content_div").html(`<a href="${knowledge_info}"><h4 class="knowledge_base">Knowledge Info</h4></a>`);

:) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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