我希望随机字符串结果(输出)显示在文本框中,以便我可以将值保存到我的数据库中。
(function() {
function IDGenerator() {
this.length = 4;
this.timestamp = +new Date;
var _getRandomInt = function( min, max ) {
return Math.floor( Math.random() * ( max - min + 1 ) ) + min;
}
this.generate = function() {
var ts = this.timestamp.toString();
var parts = ts.split( "" ).reverse();
var id = "TEST";
for( var i = 0; i < this.length; ++i ) {
var index = _getRandomInt( 0, parts.length - 1 );
id += parts[index];
}
return id;
}
}
document.addEventListener( "DOMContentLoaded", function() {
var btn = document.querySelector( "#generate" ),
output = document.querySelector( "#output" );
btn.addEventListener( "click", function() {
var generator = new IDGenerator();
output.innerHTML = generator.generate();
}, false);
});
})();
<p><button id="generate">Generate</button></p>
<p><code id="output"></code></p>
有关如何解决此问题的任何想法?因此,每次点击生成按钮时,结果都会显示在文本框中,然后将值保存到我的数据库中。
答案 0 :(得分:1)
(function() {
function IDGenerator() {
this.length = 4;
this.timestamp = +new Date;
var _getRandomInt = function( min, max ) {
return Math.floor( Math.random() * ( max - min + 1 ) ) + min;
}
this.generate = function() {
var ts = this.timestamp.toString();
var parts = ts.split( "" ).reverse();
var id = "TEST";
for( var i = 0; i < this.length; ++i ) {
var index = _getRandomInt( 0, parts.length - 1 );
id += parts[index];
}
return id;
}
}
document.addEventListener( "DOMContentLoaded", function() {
var btn = document.querySelector( "#generate" ),
output = document.querySelector( "#output" );
btn.addEventListener( "click", function() {
var generator = new IDGenerator();
$("#output").val(generator.generate());
}, false);
});
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><button id="generate">Generate</button></p>
<input type="" id="output" name="">
答案 1 :(得分:0)
只需按输入标记
替换代码标记即可<p><input id="output" type="text" value="" /></p>
并将output.innerHTML替换为
output.value= generator.generate();
希望得到帮助