模板:
<button class="r receive_code">获取验证码</button> <span class="r code"></span>
脚本:
// 生成六位数字验证码 $(".code").html(null); function createCode() { var code = ""; var length = 6; var i; var str = ""; var content; var codeSpan = $(".code"); var arrColor = ["blue", "red", "green", "brown", "gray", "pink", "red", "green", "brown", "blue"]; codeSpan.html(null); for (i = 0; i < length; i++) { index = Math.floor(Math.random() * 6); code = Math.floor(Math.random() * 10); str += code; color = arrColor[index]; content = $("<i></i>").html(code); content.appendTo(codeSpan); $(".code i").eq(index).css({"color": color}); } codeSpan.attr("data-val", str); } $(".receive_code").click(createCode);