简体   繁体   中英

Inserting a letter/number sequence to multiple child span tags using .text(). Is there a more efficient way?

I need to use specific letters of the alphabet to insert into a number of span tags, maybe 20 lets say. Do I need 20 lines of .text() or is there a more efficient way? Thanks.

$(document).ready(function(){
    $(".owl-page:first-child span").text("A");
    $(".owl-page:nth-child(2) span").text("C");
    $(".owl-page:nth-child(3) span").text("D");
    $(".owl-page:nth-child(4) span").text("E");
    $(".owl-page:nth-child(5) span").text("F");
});

Similar to the other answers but slightly different approach:

JS Fiddle

var letters = {
    1: 'A',
    2: 'B',
    3: 'C',
    4: 'D',
    5: 'E',
    6: 'F'
}

$.each(letters, function(e) {
  $('.owl-page:nth-child(' + e + ') span').text(this);
});

You can put the letters in an array and use them with .each() method.

var letters = ['A', 'C', 'D', 'E', 'F'];
var counter = 0;

$(".owl-page > * span").each(function(){ 
    if(counter >= letters.length) 
        return false; 
    $(this).text(letters[counter]);
    counter++;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM