【问题标题】:How do you replace text with a link tag when using .hover()?使用 .hover() 时如何用链接标签替换文本?
【发布时间】:2016-10-21 10:09:40
【问题描述】:

我正在尝试在包含<a>Instagram</a><a>Email</a> 的网站(使用jQuery)的导航栏中创建一个“联系人”部分,但仅当我将鼠标悬停在#contact 上时才会出现。

到目前为止,当我将鼠标悬停在 #contact 上时,我只能让字符串出现。

HTML:

<span id="contact">CONNECT</span>

jQuery:

$("#contact").hover(function(){
  $(this).text(function(i, text){
    return text === "CONNECT" ? "Instagram | Email" : "CONNECT";
  })
});

我怎样才能让“Instagram”和“电子邮件”成为链接?

我试过了:

$("#contact").hover(function(){
    $(this).text(function(i, text){
        return text === "CONNECT" ? "<a>Instagram</a> | <a>Email</a>" : "CONNECT";
    })
});

但是当我悬停时,我得到了 "&lt;a&gt;Instagram&lt;/a&gt;""&lt;a&gt;Email&lt;/a&gt;" 作为字符串而不是链接。

任何帮助将不胜感激!

【问题讨论】:

    标签: javascript jquery html web jquery-hover


    【解决方案1】:

    如果需要设置HTML而不是.text(),则需要使用.html()进行更新。

    jQuery(function($) {
      $("#contact").hover(function() {
        $(this).html(function(i, text) {
          return $(this).text() === "CONNECT" ? "<a>Instagram</a> | <a>Email</a>" : "CONNECT";
        })
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <span id="contact">CONNECT</span>

    【讨论】:

    【解决方案2】:

    我认为这样做的一个好方法是创建两个链接元素并将它们附加到“CONNECT”跨度,如下所示:

    $("#contact").hover(
      function(){
        $( '#contact' ).empty();//Remove everything
    
        $("<a>", {
        text: 'Instagram',
        title: "Instagram",
        href: "www.instagram.com"
        }).appendTo( '#contact' );
    
        $("<span>", {
        text: ' | ',
        }).appendTo( '#contact' );
    
        $("<a>", {
        text: 'Email',
        title: "Email",
        href: "mailto:name@gmail.com"
        }).appendTo( '#contact' );  
    },function(){
        $( '#contact' ).empty();//Remove everything
        $( '#contact' ).text("CONNECT");  
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <span id="contact">CONNECT</span>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-17
      • 2013-06-19
      • 2018-04-18
      • 1970-01-01
      • 2016-03-19
      • 2011-07-28
      • 2018-03-22
      • 1970-01-01
      相关资源
      最近更新 更多