我目前正在使用此代码:
var wordRandomizer = {
run: function (targetElem) {
var markup = this.createMarkup();
targetElem.appendChild(markup);
},
createMarkup: function () {
var that = this;
var frag = document.createDocumentFragment();
this.elem = document.createElement('span');
var button = document.createElement('button');
button.innerText = 'Change Item';
button.addEventListener('click', function () {
that.changeItem();
});
frag.appendChild(this.elem);
frag.appendChild(button);
return frag;
},
changeItem: function () {
var rand = this.getRandInt(1, this.items.length) - 1;
console.log(rand);
this.elem.innerText = this.items[rand];
},
getRandInt: function (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
},
items: ['itemA', 'itemB', 'itemC', 'itemD']
};
wordRandomizer.run(document.body);
我的代码是一个按钮,按下时按下列表中的一个项目。但是,我不希望项目显示在与生成器相同的页面上,因为人们只需查看源代码。按下按钮后如何才能这样做呢?它从其他位置抓取随机项目,人们无法使用源代码查看它们。
如果有帮助,您可以在此处查看代码 - http://jsbin.com/ESOdELU/1/edit
答案 0 :(得分:0)
我将使用PHP为您提供解决方案,因为它是一种免费的脚本语言,并且最有可能得到主机或默认Web服务器的支持...
首先,这里是包含jquery和基本AJAX脚本的代码
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/JavaScript">
$(document).ready(function(){
$("#generate").click(function(){
$("#madlibs p").load("script.php");
});
});
</script>
以下是 script.php
的代码<?php
header("Cache-Control: no-cache");
// For testing you can use an inline array like the lines below
// Just remove the comment slashes "//" from the beginning of the line
// and comment out the external declarations
//$actors = array('Denzel Washington','Michael J. Fox','Jim Carey','Boris Kodjoe');
//$roles = array('Mental Patient','Homeless Musician','Drag Queen Detective','Tormented Mathematician');
// In production, you would put these in a text file or a database.
// For $actors, put an entry on each line of a text file and save it as 'leads.txt'
// Do the same with a separate file for $roles (roles.txt).
$actors = file("leads.txt");
$roles = file("roles.txt");
// This selects a random element of each array on the fly
echo $prefixes[rand(0,count($actors)-1)] . " stars as a "
. $suffixes[rand(0,count($roles)-1)] . " in the next blockbuster film.";
// Example output:
// Michael J. Fox stars as a Tormented Mathematician in the next blockbuster film.
?>
将它放在页面正文中,并确保将所有内容设置为显示。
<body>
<div id="madlibs"><p> </p></div>
<button id="generate">Surprise Me!</button>
</body>
几点说明: - 您可以在script.php文件中包含基本布局HTML,然后只需要在其中显示结果的DIV的ID $(“#madlibs”)
以下是帮助我完成类似项目的原始教程的链接: http://www.sitepoint.com/ajax-jquery/
我希望这会有所帮助。对不起,但午餐时我无法想出一个纯Java的JavaScript解决方案。