首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用jQuery创建超文本链接

使用jQuery创建超文本链接
EN

Stack Overflow用户
提问于 2018-06-27 04:13:53
回答 4查看 4.2K关注 0票数 -3

多亏了快速帮助,这个问题才得以解决:

HTML

<a id="myid" href="#">What ever goes here</a>

jQuery

$("#myid").attr("href");

我需要一个使用jQuery创建的超文本标记语言链接。该链接位于图像上。我只需要得到实际的网站网址,并得到该链接的href。

<a href=" + the link created from jQuery + "><img src="myimage.jpg" /></a>

我发现了一些有帮助的类似问题,但它们都以OnClick事件结束,例如一个按钮左右。我不想要一个按钮,但在页面加载时创建的锚链接。我在很久以前就做过一些JavaScript,而jQuery对我来说还是个新手。

虽然我设法获得了这个对象,我需要一个示例,以及我如何将它加载到锚链中。

$(location).attr('href');
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2018-06-27 04:18:25

$("a").attr("href", "http://www.yoursite.com")

这将为所有a标记设置href属性。

$("#myid").attr("href", "http://www.yoursite.com/")

如果为a标记设置了id=myid

确保在代码中添加jQuery。

票数 3
EN

Stack Overflow用户

发布于 2018-06-27 04:32:30

jQuery

var $link = $("<a></a>");                          // Creates the link element.
$link.attr("href", "https://WhateverYouWant.com"); // Sets the href attribute to a particular link.
$("body").append($link);                           // Adds the link to the bottom of your page.

JavaScript

var link = document.createElement("a");                      // Creates the link element.
link.setAttribute("href", "https://WhateverYouWant.com");    // Sets the href attribute to a particular link.
document.getElementsByTagName("body")[0].appendChild(link);  // Adds the link to the bottom of your page.
票数 1
EN

Stack Overflow用户

发布于 2018-06-27 04:34:54

只要你点击例子中的按钮,你就会得到图片的链接:)享受吧!

$( '#myButton' ).click( function() {

  $('img').each( function(i,e) {
    let link = document.createElement('a');
    $(link).attr('href', $(e).attr('src'));
    $(link).append( $(e).clone() );
    $(e).replaceWith( link );
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<img src="http://via.placeholder.com/100x200">
<img src="http://via.placeholder.com/200x200">
<img src="http://via.placeholder.com/300x200">
<br/>
<button id="myButton">Make links for images!</button>

如果希望在页面加载时使用链接装饰图像,请在$(document).ready(function...)中使用img each

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51050728

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档