Change the color of random letters in a paragraph

2019-05-09 13:48发布

I want to change color of some random characters in a paragraph to red on a button click. Please find my code. I am having some errors in this.

$('input').click(function(){

   var para = $('#para');
   var position = Math.floor(Math.random()*100);
   var character = [];

   var i=0
   while ( i <= 30 )
   {
      character[i] = para.html().substr(position*(i+1), 1);
      i++;
   }

   $.each(character, function() {
     character.css('color','red');
   });

});

First of all I created an array which would contain 30 random letters from a paragraph Next I used each() to iterate over each of the elements in the array to apply the css property. But an error pops up in the console window saying object has no method 'css'

What am i doing wrong ?

2条回答
走好不送
2楼-- · 2019-05-09 14:06

You need to review the documentation for $.each. A possible solution:

$('input').click(function() {

    var $para = $('#para');
    var position = Math.floor(Math.random()*100);
    var character = [];

    for ( var i=0; i <= 30; i++ ) {
        character[i] = $("<span>" + $para.text().substr(position*(i+1), 1) 
                                  + "</span>");
        character[i].css('color', 'red');
    }

    $para.empty();

    $.each(character, function(idx, val) {
        $(val).appendTo($para);
    });
});
查看更多
放荡不羁爱自由
3楼-- · 2019-05-09 14:29

First of all, CSS method will work only on jquery objects. You have strings in character array. css method won't work on strings.

Secondly, Your each method is written wrong. It should be like this

$.each(character, function(index, value) {
    // Do something
});

For your problem statement, to change color of some random characters in your string. Here is Fiddle. Try this out.

Here is code:

$('input').click(function(){

var para = $('#para');
var charArray = $('span', para);

// case: No span (Initial String)
if (charArray.length === 0) {
    var html = para.html();
    var newArr = [];
    var len = html.length;
    for (var i=0; i<len; i++) {
        newArr.push('<span>' + html[i] + '</span>');
    }
    html = newArr.join('');
    para.html(html);
    charArray = $('span', para);
}

// Reset all spans
$.each(charArray, function(i, value) {
    value.style.color = '';
});

var paralen = charArray.length;

for (var i=0; i<30; i++) {
    var pos = Math.floor(Math.random()*100);
    pos = pos % paralen;
    charArray[pos].style.color = 'red';
}

});
查看更多
登录 后发表回答