Reputation: 2551
I'm still learning jQuery - So I'm sorry if I'm asking a lot, or if what I'm asking is easy or silly.
When I have a question I usually try to give an example of what I've tried but I honestly don't know where to start! So even some guidance on what I need to do would be more than okay! I'm more than willing to try and do this myself, I'm just not sure what to Google!
Basically what I want to do is get content of my Anchors and add them to a tracking attribute. And then the spaces in the attribute be swapped to +'s
Code:
<a href="#" tracking="Banner-_-Link+1-_-">LINK ONE</a>
<a href="#" tracking="Banner-_-Link+2-_-">LINK TWO</a>
Code After Load
<a href="#" tracking="Banner-_-Link+1-_-LINK+ONE">LINK ONE</a>
<a href="#" tracking="Banner-_-Link+2-_-LINK+TWO">LINK TWO</a>
Any guidance would be really appreciated!
Thanks!
Upvotes: 0
Views: 161
Reputation: 2216
the simplest way is to hange your html to this:
<a href="#" tracking="Banner-_-Link+1-_-" onclick=$(this).attr('tracking',$(this).attr('tracking')+$(this).text().replace(' ', '+'))>LINK ONE</a>
Upvotes: 0
Reputation: 1425
A better approach to do it is maybe adding it to a data attribute:
<a href="#" data-tracking="Banner-_-Link+1-_-">LINK ONE</a>
You can access it by using data
method:
$('a').data('tracking'); //Banner-_-Link+1-_-
I don't know why you want to change it on the fly, but anyway, you can..
$('a').each(function() {
var anchor = $(this),
anchorData = anchor.data('tracking'),
text = anchor.text().replace(' ', '+');
anchor.data('tracking', anchorData += text);
});
Just make sure you got the correct scope on selecting those a
with jQuery, otherwise you will get all anchors from your page.
Upvotes: 0
Reputation: 6190
HTML:
<a href="#" class="click-this" tracking="Banner-_-Link+1-_-">LINK ONE</a> <!--Added Class 'click-this'-->
<a href="#" class="click-this" tracking="Banner-_-Link+2-_-">LINK TWO</a>
Jquery:
$('.click-this').on('click', function(){ //On click of the anchor tag
var a = $(this).text(); //Take the text content of the one that's being clicked
var b = $(this).attr('tracking'); //take the existing content of attribute 'tracking'
b = b+a; //concatenating the two
$(this).attr('tracking', b); //reassigning the new value to attribute
});
Read up a lot on Jquery using their docs.
Learn more about .attr()
here: http://api.jquery.com/attr/
Upvotes: 0
Reputation: 36438
Piece-by-piece:
Get all links with a tracking
attribute:
var anchors = $('a[tracking]');
and loop through them:
anchors.each( function() {
at each point, get the a
element and its text (replacing ' '
with '+'
):
var a = $(this);
var txt = a.text().replace(' ', '+');
and append that text to the existing attribute:
a.attr('tracking', a.attr('tracking') + txt);
and we're done.
});
Example: http://codepen.io/paulroub/pen/Extrl
Upvotes: 3