从1和0的字符串中选择随机数并更改颜色

时间:2016-02-09 06:57:28

标签: javascript jquery random

我有一串随机1和0通过jQuery显示。我现在想选择一个随机数并改变它的颜色。使用数组或$(div).text()字符串更好吗?我可以从任一个中获取一个数字,但是如何将其插回到div中?

 var numbArray = [];

 for(i=0; i<10; i++)
 {
   var randomNumbers = Math.round(Math.random());
   $('#numbs').prepend(randomNumbers);
   numbArray[i] = randomNumbers;
 }

<div id="numbs">0000110111 </div>

上面的div是代码的结果,但是如何选择随机项,更改颜色并在原始输出中显示?

谢谢,

6 个答案:

答案 0 :(得分:1)

您可以在某个索引处找到该数字,用所需颜色包装它并重建字符串并使用html()将其重新设置为div并使用Math.floor(Math.random() * 10)从零生成随机数到你所拥有的角色的长度。

var index = 3;
var originalElementValue;

function colorStringValue(strIndex)
{
  strIndex = parseInt(strIndex);
  
  var character = originalElementValue.charAt(strIndex);
  $("#numbs").html(originalElementValue.substr(0, strIndex) + "<span style='color:red'>" + character + "</span>" +  originalElementValue.substr(strIndex+1));
  
  }



$(document).ready(function(){

  originalElementValue = $("#numbs").text();
  colorStringValue(index);
  
  $("#strIndex").click(function(){
  
       var rand = Math.floor(Math.random() * 10) + 0  ;
    $("#rand").html(rand);
        colorStringValue(rand);
  
  });


});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="strIndex" > Generate Random Number </button>
<br />

Random Number : <span id="rand"></span>

<br />

<div id="numbs">0000110111</div>

答案 1 :(得分:1)

您需要从数字字符串中选择一个随机索引,并在该特定数字周围添加一些元素,以使其具有某种风格。

var number = '0000110111';

var index = Math.floor(Math.random() * number.length);

for(var i = 0; i < number.length; i++) {
  var n = number.charAt(i);
  if(i == index) {
    $('#numbs').append($('<span/>').css('color', 'red').text(n));
  } else {
    $('#numbs').append(n);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="numbs"></div>

答案 2 :(得分:0)

var numbArray = [];

for(i = 0; i< 10; i++) {
    var randomNumbers = Math.round(Math.random());
    numbArray[i] = randomNumbers;
    $('#numbs').prepend(number);
}
var randomNumberSelection = numbArray[Math.floor((Math.random() * (numbArray.length-1)) + 1)];

$('#numbs').html("");

var number;
for(number in numbArray) {
    if(number == randomNumberSelection) {
        var colorColorCodedNumber = ""+number;
            colorColorCodedNumber = colorColorCodedNumber.fontcolor("blue");//blue!
        $('#numbs').prepend(colorColorCodedNumber);
    } else {
        $('#numbs').prepend(number);
    }
}

我相信你正在寻找与此相关的东西,或者至少这是我从你所要求的东西中获取的东西。

在这个例子中,请注意,我们会看到我们清除该元素,然后简单地重复您之前存储的数组。这就是你如何更新&#39;它

答案 3 :(得分:0)

如果我理解正确的问题,你想为div中的特定位置设置颜色。这意味着您必须在具有特定颜色的随机位置处创建div内的span(或其他html元素)。我没有在下面测试过这段代码,但我想你可能会这样:(在本例中为随机项目的红色)

var randomIndex= Math.floor(Math.random() * 9); //Random number between 0 and 9.
var currentContent = $("#numbs").html(); 
var randomItem= currentContent.charAt(randomIndex);

newContent = '';
for(i=0; i<10; i++) {
    if (i == randomIndex) {
        newContent = newContent + 
        '<span style="background:red;">' + randomItem + '</span>';
    }
    else {
        newContent = newContent + currentContent.charAt(i);
    }
}

$("#numbs").html( newContent );

答案 4 :(得分:0)

这是你在找什么?我试了一下。 :)

     var numbArray = [];
     var sample = "<span style='color:#%COLOR%'>%NUM%</span>";
     for(i=0; i<10; i++)
     {
       var randomNumbers = Math.round(Math.random());
       var html = sample.replace('%NUM%', randomNumbers);
       var randomColor = Math.round((Math.random()* 100000000 )%16777215).toString(16);
       html = html.replace('%COLOR%', randomColor);
       $('#numbs').prepend(html );
       numbArray[i] = randomNumbers;
     }

我以为你也想要随机颜色。

答案 5 :(得分:0)

所有人的好答案;谢谢!我没想到附加DOM和重新显示。我去为每个号码分配一个id,然后使用css而不添加。我正在寻找可以变成颜色的数字,当所有数字都是那种颜色时,脚本会停止。我不知道哪种方法表现最好,但这种方式对我的数量有限。

Option Explicit
Dim dTime As Date
Dim dTime2 As Date

'------------------------------------------------------------
'This is what checks cells to define if an email notification has to be sent, and what the content of that email should be.
'------------------------------------------------------------
Function TaskTracker()
Dim FormulaCell     As Range
Dim FormulaRange    As Range
Dim NotSentMsg      As String
Dim MyMsg           As String
Dim SentMsg         As String
Dim SendTo          As String
Dim CCTo            As String
Dim BCCTo           As String
Dim MyLimit         As Double
Dim MyLimit2        As Double

dTime = Now() + TimeValue("00:01:00")
NotSentMsg = "Not Sent"
SentMsg = "Sent"
SendTo = ThisWorkbook.Worksheets("Tasks").Range("D2")
CCTo = ThisWorkbook.Worksheets("Tasks").Range("E2")
BCCTo = ThisWorkbook.Worksheets("Tasks").Range("F2")

MyLimit = Date
MyLimit2 = ((Round(Now * 1440, 0) - 30) / 1440)

Set FormulaRange = ThisWorkbook.Worksheets("Tasks").Range("F5:F35")
On Error GoTo EndMacro:
For Each FormulaCell In FormulaRange.Cells
    With FormulaCell
            If DateValue(CDate(.Value)) = MyLimit Then
                MyMsg = SentMsg
                If .Offset(0, 1).Value = NotSentMsg Then
                    strTO = SendTo
                    strCC = CCTo
                    strBCC = BCCTo
                    strSub = "[Task Manager] Reminder that you need to: " & Cells(FormulaCell.Row, "B").Value

                If Cells(FormulaCell.Row, "C").Value = "" Then
                        strBody = "Greetings, " & vbNewLine & vbNewLine & _
                        "Your task : " & Cells(FormulaCell.Row, "B").Value & " is nearing its Due Date: " & Cells(FormulaCell.Row, "F").Value & "." & vbNewLine & "A wise decision would be to complete this task before it expires!" & _
                        vbNewLine & vbNewLine & "Truly yours," & vbNewLine & "Task Manager"
                Else
                        strBody = "Hello, " & vbNewLine & vbNewLine & _
                        "Your task : " & Cells(FormulaCell.Row, "B").Value & " with the mention: " & Cells(FormulaCell.Row, "C").Value & " is nearing its Due Date: " & Cells(FormulaCell.Row, "F").Value & "." & vbNewLine & "A wise decision would be to complete this task before it expires!" & _
                        vbNewLine & vbNewLine & "Truly yours," & vbNewLine & "Task Manager"
                End If
        If sendMail(strTO, strSub, strBody, strCC) = True Then MyMsg = SentMsg
        End If

            Else
            MyMsg = NotSentMsg
            End If

            If .Value = MyLimit2 Then
            MyMsg = NotSentMsg
        End If

            Application.EnableEvents = False
            .Offset(0, 1).Value = MyMsg
            Application.EnableEvents = True

    End With

Next FormulaCell

ExitMacro:
Exit Function

EndMacro:
Application.EnableEvents = True

MsgBox "Some Error occurred." _
     & vbLf & Err.Number _
     & vbLf & Err.Description

Application.OnTime dTime, "TaskTracker", , True

End Function
'------------------------------------------------------------
'This is the function that clears the rows of Completed Tasks
'------------------------------------------------------------
Function AutoClear()
Dim i As Integer

dTime2 = Now() + TimeValue("00:01:00")

With Tasks
    For i = 5 To 35
         If .Cells(i, 4).Value Like "Done" And .Cells(i, 5).Value = "1" Then
            .Cells(i, 1).ClearContents
            .Cells(i, 2).ClearContents
            .Cells(i, 3).ClearContents
            .Cells(i, 5).ClearContents
            .Cells(i, 6).ClearContents
            .Cells(i, 4).Value = "Pending"
            .Cells(i, 7).Value = "Not Sent"

        End If
    Next i
End With

Tasks.AutoFilter.ApplyFilter
Application.OnTime dTime2, "AutoClear", , True

End Function
'------------------------------------------------------------
'ThisWorkbook calls this to deactivate the Application.OnTime. This "should" prevent the Excel process from reoppening the worksheets.
'------------------------------------------------------------

Function AutoDeactivate()
On Error Resume Next
Application.OnTime EarliestTime:=dTime, Procedure:="TaskTracker", _
    Schedule:=False
Application.OnTime EarliestTime:=dTime2, Procedure:="AutoClear", _
    Schedule:=False
End Function