如何将 var 添加到 href
我需要这样的东西:
var link = " http://www.google.com";
<a href='link' />
所以我需要使用一个变量作为链接的 href
属性。这可能吗?
它与 ""
配合使用。有更好的办法吗?
I need something like this:
var link = " http://www.google.com";
<a href='link' />
So I need to use a variable as href
attribue of a link. Is this possible?
It worked with "<a href= '" + link + "' />"
. Is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您应该在服务器上设置 href 值,为此使用脚本是糟糕的设计。
然而,要回答这个问题,可以通过使用脚本在 DOM 中设置 A 元素的 href 属性来完成,例如:
当然还有一千种其他方法,但都有其缺陷。所以在服务器上设置该值并避免它们。
You should set the href value on the server, it is bad design to use scripting for this.
However, to answer the question, it can be done by using script to set the href property of the A element once it is in the DOM, e.g.:
Of course there are a thousand other ways, all with their pitfalls. So set the value on the server and avoid them all.
使用 jQuery 这将是
虽然这不会优雅地降级如果 javascript 被关闭并且你可能想要使用其他东西而不是通过 href 进行选择。
Using jQuery this would be
Though this would not degrade gracefully should javascript be turned off and you'd probably want to use something else rather than selecting by the href anyways.
如果您实际上正在编写这两行代码,那么使用 write
Google
会更容易否则,您将需要使用 JavaScript 来设置链接的
href
属性,这将需要获取对其的引用(这意味着您应该设置其id
属性)。因此,您可以编写如下内容:
Google
并在 JavaScript 中编写:
document.getElementById("myLink").href=link
但首先,请考虑这是否真的有必要(或在您的问题中提供更多详细信息)。
If you are actually writing both of those lines of code, it would be much easier to use write
<a href="http://www.google.com">Google</a>
Otherwise, you will need to use JavaScript to set the
href
property of your link, which will require getting a reference to it (which means you should set itsid
property).So you could write something like:
<a id="myLink">Google</a>
and in your JavaScript have:
document.getElementById("myLink").href=link
but first, please think about whether this is really necessary (or provide some more details in your question).
您正在使用 Jetpack,因此可以执行
.toXMLString()
。如果您只想创建
元素,请使用以下内容。
You're using Jetpack, so you can do
<a href={link}/>.toXMLString()
.If all you want to do is create an
<a/>
element, use the following.