使JavaScript的超链接

使JavaScript的超链接

本文介绍了使JavaScript的超链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在HTML页面中使用超链接字符串,我想在我的js文件中声明源链接(URL)。请告诉我如何从我的js调用该网址到html中。



谢谢

解决方案

有很多不同的方法可以做到这一点。您可以使用创建一个链接元素,然后注入元素放入DOM中。或者您可以使用页面上已有的元素的 .innerHTML 属性来插入使用文本的链接。或者您可以修改页面上现有链接的href属性。所有这些都是可能的。这里有一个例子:

使用DOM方法创建/插入DOM节点

  var link = document.createElement('a'); 
link.textContent ='链接标题';
link.href ='http://your.domain.tld/some/path';
document.getElementById('where_to_insert')。appendChild(link);

假设您在HTML中有这样的内容:

 < span id =where_to_insert>< / span> 

使用innerHTML创建/插入DOM内容



另一个使用 innerHTML 的例子(你通常应该避免出于安全考虑而使用它,但在你完全控制HTML被注入):

  var其中= document.getElementById('where_to_insert'); 
where.innerHTML ='< a href =http://your.domain.tld>链接标题< / a>';

更新命名DOM节点的属性



最后,有一种方法只更新现有链接的href属性:

  document.getElementById('link_to_update')。href ='http://your.domain.tld/path'; 

...假设您在HTML中具有以下内容:

 < a id =link_to_updatehref =javascript:void(0)>链接标题< / a> 


I want to use a hyperlink string in HTML page which I want to declare source link (URL) in my js file. Please tell me how can I call that URL from my js into html.

Thanks

解决方案

There are a number of different ways to do this. You could use document.createElement() to create a link element, and then inject the element into the DOM. Or you could use the .innerHTML property of an element that you already have on the page to insert the link using text. Or you could modify the "href" attribute of an existing link on the page. All of these are possibilities. Here is one example:

Creating/Inserting DOM Nodes with DOM Methods

var link = document.createElement('a');
link.textContent = 'Link Title';
link.href = 'http://your.domain.tld/some/path';
document.getElementById('where_to_insert').appendChild(link);

Assuming you have something like this in your HTML:

 <span id="where_to_insert"></span>

Creating/Inserting DOM Content with innerHTML

And another example using innerHTML (which you should generally avoid using for security reasons, but which is valid to use in cases where you completely control the HTML being injected):

 var where = document.getElementById('where_to_insert');
 where.innerHTML = '<a href="http://your.domain.tld">Link Title</a>';

Updating the Attributes of a Named DOM Node

Lastly, there is the method that merely updates the href attribute of an existing link:

 document.getElementById('link_to_update').href = 'http://your.domain.tld/path';

... this assumes you have something like the following in your HTML:

 <a id="link_to_update" href="javascript:void(0)">Link Title</a>

这篇关于使JavaScript的超链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 13:40