Reputation: 497
I'm trying to write some code which will append the href of links after them when a button is clicked. So:
would turn to
My code just puts (www.google.com) after every link, however. I suspect I'm meant to use $.each()
in some way, but can't find an online example which doesn't just return a string.
My code is:
$(document).on('click', "#button", function(){
$("a").each(function(){
var www = $("a")
.attr("href")
.replace('http://',' (');
$("a").after(www + ')');
});
});
How can I amend it to add the correct links? Thank you.
Upvotes: 0
Views: 39
Reputation: 1
first you need to add the same class to the links
<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>
Second you will have to create on object with all the different links
$(document).on('click', "#button", function(){
var links = $('.link');
$.each(links, function(index,value){
var www = value.attr("href").replace('http://',' (');
$(this).after(www + ')');
});
});
This should work, as i use it all the time, the only thing that i have not tried is the .after()
Upvotes: 0
Reputation: 24648
When the page loads, you would have to save the default value to be used as the base text for each click of the link.
$(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>
Upvotes: 0
Reputation: 4243
Just get the attribute of the current item when you iterate through the each
fucntion:
$(document).on('click', "#button", function(){
$("a").each(function(){
var $this = $(this);
var www = $this.attr("href").replace('http://',' (');
$this.after(www + ')');
});
});
Upvotes: 0
Reputation: 45106
You need to get attribute of the current element. Which is accessible through current function context.
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>
Upvotes: 1