2014-11-21 58 views
0

我试图写一些代码,当点击一个按钮时,它们会在后面添加链接的href。所以:在jQuery中返回不同的属性

  • 谷歌
  • 亚马逊
  • Facebook的

将转向

  • 谷歌(www.google.com)
  • 亚马逊(www.amazon.com )
  • Facebook(www.facebook.com)

但是,我的代码只是放在每个链接之后(www.google.com)。我怀疑我打算以某种方式使用$.each(),但无法找到不仅仅返回字符串的在线示例。

我的代码是:

$(document).on('click', "#button", function(){ 
    $("a").each(function(){ 
     var www = $("a") 
        .attr("href") 
        .replace('http://',' ('); 
     $("a").after(www + ')'); 
    }); 
}); 

我如何修改它来添加正确的链接?谢谢。

回答

1

您需要获取当前元素的属性。可以通过当前的功能上下文访问。

var $this = $(this), 
    www = $this.attr("href").replace('http://',' ('); 
$this.after(www + ')'); 

$('#links').click(function(){ 
 
    $('a').each(function() { 
 
    var $this = $(this); 
 
    
 
    $this.after($this.attr('href')); 
 
    }); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button id="links">Links</button> 
 
<a href="http://google.com">Google</a> 
 
<a href="http://foogle.com">foogle</a> 
 
<a href="http://boogle.com">boogle</a>

+0

谢谢 - 我早些时候尝试过。它只是因为某种原因在每个链接之后添加了所有三个href。 – JohnG 2014-11-21 15:46:19

+0

@JohnG尝试它的代码片段。 – 2014-11-21 15:49:33

+0

真棒 - 非常感谢,您的扩展版本只是诀窍。 – JohnG 2014-11-21 15:55:25

0

刚刚获得当前项目的属性,当你通过each温控功能迭代:

$(document).on('click', "#button", function(){ 
    $("a").each(function(){ 
    var $this = $(this); 
    var www = $this.attr("href").replace('http://',' &#40;'); 
    $this.after(www + '&#41;'); 
    }); 
}); 
0

页面加载后,你会救默认值将用作每次链接点击的基本文本。

$(document).ready(function() { 
 
    
 
    //Save the initial text of the link 
 
    $('ul li a').attr('data-default', function() { 
 
    return $(this).text(); 
 
    }); 
 
    
 
    $('ul li a').on('click', function(e) { 
 
    
 
    //prevent default action 
 
    e.preventDefault() 
 
    
 
    //append the value of href property to initial value and set as test of link 
 
    $(this).text(function() { 
 
     return $(this).data('default') + ' (' + this.href + ') '; 
 
    }); 
 
    
 
    }); 
 
    
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<ul> 
 
    <li><a href="http://www.google.com">Google</a></li> 
 
    <li><a href="http://www.amazon.com">Amazon</a></li> 
 
    <li><a href="http://www.facebook.com">Facebook</a></li> 
 
</ul>

0

首先你需要在同一类添加到链接

<a href='www.google.com' class='link' >google</a> 
<a href='www.google2.com' class='link' >google2</a> 
<a href='www.google3.com' class='link' >google3</a> 

其次,你必须创建对象的所有不同的环节

$(document).on('click', "#button", function(){ 
    var links = $('.link'); 
    $.each(links, function(index,value){ 
     var www = value.attr("href").replace('http://',' &#40;'); 
     $(this).after(www + '&#41;'); 
    }); 
}); 

这应该工作,因为我一直使用它,o最后,我还没有尝试过的是.after()