【问题标题】:Create HTML link using jQuery [closed]使用 jQuery 创建 HTML 链接 [关闭]
【发布时间】:2018-06-26 20:13:53
【问题描述】:

感谢快速帮助,问题已解决:

HTML

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

jQuery

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

我需要一个使用 jQuery 创建的 HTML 链接。链接在图像上。 我只需要获取实际的网站 url 并将其放入链接的 href 中。

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

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

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

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

【问题讨论】:

  • 所以我不清楚你想要的 href 值是什么。
  • 我需要访问者所在网站的实际网址,而不是静态网址。这说明清楚了吗?

标签: javascript jquery


【解决方案1】:
$("a").attr("href", "http://www.yoursite.com")

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

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

如果您为a 标签设置了id=myid

确保在代码中添加 jQuery。

【讨论】:

  • 当然是我要找的“id”属性!谢谢你:)
【解决方案2】:

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.

【讨论】:

    【解决方案3】:

    如果你想把当前页面的url放到链接中,你只需要抓住它。

    var pageUrl = window.location.href;
    var newLink = '<a href="'+ pageUrl +'"><img src="myimage.jpg" /></a>';
    
    //do whatever you want with newLink
    

    【讨论】:

      【解决方案4】:

      只要单击示例中的按钮,您就会获得图像链接:) 享受吧!

      $( '#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

      【讨论】:

        猜你喜欢
        • 2014-12-12
        • 2015-02-13
        • 1970-01-01
        • 2018-09-19
        • 2017-08-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多