2014-04-20 151 views
-3

我碰到過這段jQuery,我想知道它的功能。我是jQuery的新手,但從我可以看到,我認爲它會將編號爲的元素替換爲以與類別html5lightbox和編號顯示的鏈接。我不明白是$('#reveal').text()被jQuery困惑

$('#reveal').replaceWith('<a class="html5lightbox" href="#" id="reveal">' + $('#reveal').text() + '</a>'); 
+0

https://api.jquery.com/text/ – jgillich

+3

*首先*當您不知道某個方法做什麼時,請查看[文檔](http://api.jquery.com/文字) –

回答

2

text()功能簡單地獲得了所述元素的組合的文本內容:

<div id="reveal"> 
    <div>Demonstration Box</div> 
    <ul> 
    <li>list item 1</li> 
    <li>list <strong>item</strong> 2</li> 
    </ul> 
</div> 

$("#reveal").text()會產生以下結果:

Demonstration Box list item 1 list item 2 

最好的問候

1

它獲得的意義是從當前#reveal文本,並使用它在新的#reveal

這將是一樣

var text = $('#reveal').text(); 

var anchor = '<a class="html5lightbox" href="#" id="reveal">' + text + '</a>'; 

$('#reveal').replaceWith(anchor); 
+0

不好的例子顯示不緩存變量的代碼。我知道你可以做得更好:) – japrescott

+0

@japrescott - 這絕對沒有區別。 – adeneo

+0

Negletable是的,但它確實有區別 – japrescott

1

它所做的是包是什麼id爲「揭示」帶有錨元素(鏈接)的元素中。所以你不明白的部分是它實際上從#reveal中提取文本,然後它被替換爲replaceWith

通常,人們會用jquery function wrap做這樣的事情。作爲一個附註 - >總是將你的$(「whatever」)緩存在一個變量中以便稍後再使用。所以你的代碼應該是;

var reveal=$('#reveal') 
reveal.replaceWith('<a class="html5lightbox" href="#" id="reveal">' + reveal.text() + '</a>'); 

reveal.wrap('<a class="html5lightbox" href="#"></a>');