使用jQuery重置每个实例的随机字符串

时间:2014-07-21 01:42:05

标签: javascript jquery

我生成一系列随机字符,这些字符将在隐藏字符后添加。我还包括用于隐藏原始邮件的脚本。

我似乎无法弄清楚如何重置"每次使用的随机字符串。当前返回的内容是每个实例的相同字符串。我想在每个隐藏字符后面插入一个随机字符串。

我做错了什么?

var message = "A random message with each character hidden in a span tag."

$(function() {  
  var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+,./?";
  var string_length = Math.ceil(Math.random() * 10) + 19;
  var randomstring = '';
  for (var i=0; i<string_length; i++) {
    var rnum = Math.floor(Math.random() * chars.length);
    randomstring += chars.substring(rnum,rnum+1);
  };

  $('body')
    .html(message)
    .children()
    .andSelf()
    .contents()
    .each(function(){
       var $this = $(this);
       $this.replaceWith($this.text().replace(/[A-Za-z0-9., ]/g, "<span hidden>$&</span>" + randomstring));
       console.log(randomstring);
       console.log(randomstring);
    });   
});

2 个答案:

答案 0 :(得分:1)

尝试将randomstring作为函数而不仅仅是变量。

var message = "A random message with each character hidden in a span tag."
function randomstring() {
  var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+,./?";
  var string_length = Math.ceil(Math.random() * 10) + 19;
  var result= '';
  for (var i=0; i<string_length; i++) {
    var rnum = Math.floor(Math.random() * chars.length);
    result+= chars.substring(rnum,rnum+1);
  };
  return result;
}

$(function() {   
  $('body')
    .html(message)
    .children()
    .andSelf()
    .contents()
    .each(function(){
      var $this = $(this);
      $this.replaceWith($this.text().replace(/[A-Za-z0-9., ]/g, "<span hidden>$&</span>" + randomstring()));
      console.log(randomstring());
      console.log(randomstring());
    });   
});

答案 1 :(得分:0)

您只创建一个randomstring并且代码已完成,然后您开始循环遍历元素并将相同的变量传递给html。

您可以使用一个简单的函数来解决这个问题,以便在each循环内按需获取新字符串。我创建了一个稍微高级的功能,也确保你没有重复

var randString = (function() {
    var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+,./?";    
    var strArray = this.strArray = [];/* store all strings created in array*/
    var createString = function () {
        var string_length = Math.ceil(Math.random() * 10) + 19;
        var randomstring = '';
        for (var i = 0; i < string_length; i++) {
            var rnum = Math.floor(Math.random() * chars.length);
            randomstring += chars.substring(rnum, rnum + 1);
        }
        return randomstring;
    }
     this.get= function () {
            var str = '';
            /* make sure output is unique*/
            while (strArray.indexOf(str) === -1) {
                str = createString();
                strArray.push(str);
           }            
            return str;
        }     
     return this;    
})();

$('body').html(message).children().andSelf().contents().each(function(){
    var randomstring = randString.get();
    /* your dom manipulation code */
});