html 链接,来自 Javascript 函数的 href 分配
我有一个简单的 Javascript 函数,它构建了一个我想要提供链接的 URL。
但是,我似乎无法让锚标记与它一起使用。如何将锚标记的 href 分配给 Javascript 函数的结果?
这些都不能正常工作:
<a href="getUrl();">Click here</a>
<a href="javascript:getUrl();">Click here</a>
这就是我想要完成的任务。
I have a simple Javascript function which builds a Url that I want to provide a link to.
However, I can't seem to get the anchor tag working with it. How do I assign the href of the anchor tag the results of the Javascript function?
Neither one of these work correctly:
<a href="getUrl();">Click here</a>
<a href="javascript:getUrl();">Click here</a>
This is what I want to accomplish.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
-- 更新 --
如果我想合并 user278064s 的评论,我会将上面的内容更改为:
-- update --
If I wanted to incorporate user278064s' comments, i would change the above into:
上述解决方案都不适合我。一个好方法是在函数中创建一个新链接。
None of the above solutions worked for me. A good way would be to create a new link in the function.
点击此处
Click Here
为链接指定一个
id
:稍后,通过 JavaScript 设置其
href
:(您可能希望在链接中包含一个占位符
href
禁用 JavaScript 将会看到。)Give the link an
id
:Later on, set its
href
from JavaScript:(You might want to include a placeholder
href
in the link which people with JavaScript disabled will see.)更新
我假设您想使用
getUrl()
方法来设置 href 属性,因为指向的 url 可能不是静态的(因此它可能随时发生变化)指向 getUrl() 返回的 url。)无论如何,当用户单击链接时,您可以通过这种方式分配 href 属性。
遵循完整的代码:
另一件事。您应该避免使用
javascript:pseudo-protocol
。该片段将向您解释原因:
DOM 脚本:使用 JavaScript 和文档对象模型进行网页设计:第二版
UPDATE
I assume that you want to use the
getUrl()
method to set the href attribute, because probably the pointed url is not static (so it could change at any moment e point to the getUrl() returned url.)Anyway, you could assign the href attribute, when i.e. the user click on the link, in this way.
Following the complete code:
One other thing. You should avoid the use of
javascript: pseudo-protocol
.This fragment will explain you why:
DOM Scripting: Web Design with JavaScript and the Document Object Model: Second Edition
以下内容对我有用
The following worked for me