2017-04-24 59 views
1

迭代與每次測驗的Jquery

$('p').each(function (index) { 
 
    var letters = $(this).text().length; 
 
$('p').appendTo('<span> Here is ' + letters + '</span>'); 
 
}); 
 

 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p>Lorem</p> 
 

 
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A amet vel fugit repellendus, magni blanditiis delectus autem dicta, omnis odit beatae iusto asperiores, iste. Delectus, eaque reiciendis quibusdam cupiditate molestias officia perspiciatis corporis cumque saepe voluptatem, magnam magni asperiores a!</p>

你好,我會感謝很多我的代碼任何幫助,我需要計算每一個<p>標籤的所有信件,並顯示在<p>標籤結束但我的代碼計算了我在頁面上所有的<p>標籤,並將它們放在每個標籤中,任何人都可以告訴我是什麼。錯了,如何解決它,謝謝你這麼多

+0

爲此使用此上下文。而不是'$('p')'使用'$(this)' – guradio

+0

非常感謝你,先生!我只是開始我的編程方式,很難理解這到底意味着什麼 –

回答

1

因爲$('p')會發現在頁面每<p>您正在使用它來建立初始查詢

你想要的each這裏面的具體實例以同樣的方式$(this)並希望append()appendTo()

$('p').each(function (index) { 
 
    var letters = $(this).text().length; 
 
    $(this).append('<span style="color:red"> Here is ' + letters + '</span>'); 
 
}); 
 

 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p>Lorem</p> 
 

 
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A amet vel fugit repellendus, magni blanditiis delectus autem dicta, omnis odit beatae iusto asperiores, iste. Delectus, eaque reiciendis quibusdam cupiditate molestias officia perspiciatis corporis cumque saepe voluptatem, magnam magni asperiores a!</p>

+0

非常感謝你,先生!我剛剛開始編程,所以很難理解這究竟意味着什麼 –

+0

如有疑問......請查看api中的示例和詳細信息... http://api.jquery.com/each/ – charlietfl

0

$('p').each(function (index) { 
 
    $('<span></span>',{text : " Here is " + $(this).text().length + ""}).css({color:'blue'}).appendTo(this); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p>Lorem</p> 
 

 
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A amet vel fugit repellendus, magni blanditiis delectus autem dicta, omnis odit beatae iusto asperiores, iste. Delectus, eaque reiciendis quibusdam cupiditate molestias officia perspiciatis corporis cumque saepe voluptatem, magnam magni asperiores a!</p>