使用随机javascript字符串元素单击按钮刷新div

时间:2015-04-27 22:00:09

标签: javascript jquery html ajax

有几个类似的问题,所以我希望这是一个独特的问题。在这些类似问题上提出的解决方案都没有解决我的问题。如果我以某种方式搞砸了,这个初学者会道歉。

我的页面上有一个空div,我使用javascript加载数组中的字符串。目前,我在一个按钮上运行脚本,重新加载整个页面。我希望该按钮只用我的javascript数组中的项目重新加载div。

这是我的代码:

<html>
<head>
<link rel="stylesheet" href="obliqueStyle.css">
<style></style>
</head>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
    <body>
        <div id="wrapper">
        <div id="strategyBox"></div>

         <div id="button">
         <a class="againbutton" onclick="buttonReload()">Again</a>

            <script>
                   var buttonReload = function() {
                        document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
                   }
            </script>
         </div>

        </div>
        <script src="os.js"></script>

    </body>

这是我的数组和JS(来自index.html中引用的os.js文件)的片段我用来在初始/刷新时加载div:

var obliqueStrategy = ["Abandon normal instruments",
                   "Accept advice",
                   "Accretion",
                   "A line has two sides"];


var randomStrategy = obliqueStrategy[Math.floor(Math.random() * obliqueStrategy.length)];


                   document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';

我尝试在html中调用与脚本中的函数相同的javascript,如下所示:

<div id="button">
         <a class="againbutton" onclick="buttonReload()">Again</a>

            <script>
                   var buttonReload = function() {
                        document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
                   }
            </script>
         </div>

我尝试过使用像这样的jQuery AJAX加载函数:

<script>
        $(function() {
            $("#againbutton").on("click", function() {
            $("#strategyBox").load("index.html")
            return false;
            })
        })
</script>

我已经玩过上面的各种变化,并尝试了其他一些我忘记我究竟是怎么做以及做了什么的事情,所以我不能包括它们。尽管看起来非常简单,但我确实在这方面遇到了障碍。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

以下是一种方法:http://jsfiddle.net/kxqcws07/

HTML

void foo_will_not_modify (const std::string &x); // const ref - won't modify
void bar_will_not_modify (std::string x);        // copy - won't modify
void baz_will_modify (std::string &x);           // reference - can modify

的Javascript

<div id="wrapper">
    <div id="strategyBox"><p id="strategyText"></p></div>
    <div>
        <input type="button" class="againbutton" value="Again">
    </div>
</div>