2014-04-20 86 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>');