2017-07-02 72 views
0

我有以下代碼,我想要將索引換成<span></span>標籤。如何在span或div標籤中包裝var?

$('h2.carousel-item-title').each(function (index, value) { 
    var content = '<span class = "wrap"></span>'; 
    var tab_number= $(this).append(index+1).wrap(content); 
    return tab_number; 
}); 

但它沒有奏效。

任何幫助,將不勝感激

+0

什麼 「它不工作」 是指在你的情況? –

+0

沒有它沒有工作,但我找到了解決方案:
$('。carousel-item-title')。each(function(index,value){ var num = index + 1; $(this).append( 「」+ num +「」); }); –

回答

0

我已經對您的代碼段進行了更改,以使其工作。

用途:

$(document).ready(function() { 
    $('.carousel-item-title').each(function (index, value) { 
    console.log('query'); 
    var content = '<span class = "wrap"></span>'; 
    var tab_number= $(this).append(index+1).wrap(content); 
    return tab_number;}); 
    }); 

完整的代碼是在這裏:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="UTF-8"> 
<title>Title</title> 

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

<script type="text/javascript"> 
$(document).ready(function() { 
    $('.carousel-item-title').each(function (index, value) { 
    console.log('query'); 
    var content = '<span class = "wrap"></span>'; 
    var tab_number= $(this).append(index+1).wrap(content); 
    return tab_number;}); 
    }); 

</script> 
</head> 
<body> 

<h2 class="carousel-item-title"> A 
</h2> 

<h2 class="carousel-item-title"> B 
</h2> 
<h2 class="carousel-item-title"> C 
</h2> 
<h2 class="carousel-item-title"> D 
</h2> 

相關問題