嘿那里:)我正在尝试创建一个函数,所以在编写文本时,用户可以单击从数组中获取随机值的按钮并放入textarea无刷新。我当前的问题是一旦页面加载,它使用onclick从php和js中的数组中获取随机值,但是单击按钮不会获得新值,在刷新之前总是一样。
我不是很JS我只使用php和一些ajax / jquery刷新调用。这是我的实际功能和代码:
function randommacro(){
$randomword = array(1, 2, 3, 4, 5);
//$randomword = file('macro/randomword.txt');
shuffle($randomword);
$randomword = $randomword[0];
return $randomword;
}
<script language="javascript" type="text/javascript">
function addtext(text) {
document.myform.message.value += text;
}
</script>
<button class="btn btn-primary" onclick="addtext('<?php echo htmlspecialchars(randommacro()); ?>'); return false">Random Macro</button>
答案 0 :(得分:1)
这将允许您使用javascript从数组中获取随机值。
<html>
<body>
<script language="javascript" type="text/javascript">
function addtext() {
$randomword = ["Name","Think","Person","Apple","Orange","bananna"];
document.myform.message.value += $randomword[getRandomInt(0,5)];
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
</script>
<form name="myform">
<textarea name="message">
</textarea>
<button type="button" onclick="addtext();">Random Macro</button>
</form>
</body>
</html>
这是一个PHP和Javascript版本:
<html>
<body>
<?php
// Create your array using PHP
$RandomTextArray = array("Name","Think","Person","Apple","Orange","bananna");
?>
<script language="javascript" type="text/javascript">
function addtext() {
// Create the Javascript version of your PHP array
$randomword = <?php echo json_encode($RandomTextArray); ?>;
// Add a new word to the textarea value
document.myform.message.value += $randomword[getRandomInt(0,<?php echo sizeof($RandomTextArray) ?>)];
}
function getRandomInt(min, max) {
// Returns a random integer between your min and max values (aka: 0 and size of array)
return Math.floor(Math.random() * (max - min)) + min;
}
</script>
<form name="myform">
<textarea name="message"></textarea>
<button type="button" onclick="addtext();">Random Macro</button>
</form>
</body>
</html>
答案 1 :(得分:0)
尝试将其放入另一个变量
$random = $randomword[0]
return $random