2014-08-31 94 views
0

我還在學習jQuery的 - 所以,我很抱歉,如果我問了很多,或者有什麼我問的是容易還是愚蠢。jQuery的 - 獲取文本從元素與添加的屬性

當我有一個問題,我通常會盡量給什麼,我已經試過一個例子,但老實說,我不知道從哪裏開始!所以即使是我需要做的一些指導也不止於此!我非常樂意嘗試自己做這件事,我只是不確定Google要做什麼!

基本上就是我想要做的就是我的錨的內容,並將它們添加到跟蹤屬性。然後在屬性的空間被交換到+的

代碼:

<a href="#" tracking="Banner-_-Link+1-_-">LINK ONE</a> 
<a href="#" tracking="Banner-_-Link+2-_-">LINK TWO</a> 

代碼加載後

<a href="#" tracking="Banner-_-Link+1-_-LINK+ONE">LINK ONE</a> 
<a href="#" tracking="Banner-_-Link+2-_-LINK+TWO">LINK TWO</a> 

任何指導意見將非常感激!

謝謝!

回答

3

件逐件:

獲取與tracking屬性的所有鏈接:

var anchors = $('a[tracking]'); 

和循環通過他們:

anchors.each(function() { 

在每個點,得到了a元素其文字(用'+'代替' '):

​​

並追加文本到現有的屬性:

a.attr('tracking', a.attr('tracking') + txt); 

,我們就大功告成了。

}); 

例子:http://codepen.io/paulroub/pen/Extrl

+0

絕對的輝煌!這正是我所需要的,你已經說得很清楚。謝謝保羅! – Nick 2014-08-31 20:36:53

0

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 
}); 

閱讀了使用他們的文檔jQuery的很多。

瞭解更多關於.attr()這裏:http://api.jquery.com/attr/

0

最簡單的方法是將HTML焊割這樣:

<a href="#" tracking="Banner-_-Link+1-_-" onclick=$(this).attr('tracking',$(this).attr('tracking')+$(this).text().replace(' ', '+'))>LINK ONE</a> 
0

一個更好的辦法來做到這一點也許是它添加到數據屬性:

<a href="#" data-tracking="Banner-_-Link+1-_-">LINK ONE</a> 

您可以通過使用data方法訪問它:

$('a').data('tracking'); //Banner-_-Link+1-_- 

我不知道你爲什麼要改變它的飛行,但無論如何,你可以..

$('a').each(function() { 
    var anchor = $(this), 
     anchorData = anchor.data('tracking'), 
     text = anchor.text().replace(' ', '+'); 
    anchor.data('tracking', anchorData += text); 
}); 

只要確保你得到的選擇那些a與jQuery正確的範圍,否則你會從你的頁面獲得所有錨點。