【问题标题】:Append content to div on click without page reloading单击时将内容附加到 div 而无需重新加载页面
【发布时间】:2016-11-25 07:02:50
【问题描述】:

在我的应用程序中,我有一个对象映射作为关联数组,它是从 JSON 中获取的。这是一张地图,其中包含问题和每个问题的四个答案。接下来,我尝试将问题附加到问题 div 和答案作为 div 答案的单选按钮。没有一件事,一切似乎都完美无缺。将内容附加到我的 div 页面后正在重新加载。所以我的问题是在这种情况下如何防止页面重新加载。我尝试使用 ajax 调用,但不幸的是我失败了。 我的代码如下:

<script>
    $(document).ready(function(){
    var questions = [];
        $.getJSON("/exam/json", function (result) {
            var map = {};
            var response = result;
            for (var i = 0, l = response.length; i < l; i++) {
                map[response[i].id] = response[i];
            }
            $('#nextButton').click(function(){
                prepareQuestion(map);
            });
        });
    });
    function prepareQuestion(questionList){
        var actualQuestionIndex = String(Math.floor(Math.random() * Object.keys(questionList).length) + 1);
        $('#question').append(questionList[actualQuestionIndex].question);
        if(questionList[actualQuestionIndex].ansc === null){
            $('#answers').append("<input type='radio' name='ansa' value='A'>"+questionList[actualQuestionIndex].ansa+"<br>");
            $('#answers').append("<input type='radio' name='ansb' value='B'>"+questionList[actualQuestionIndex].ansb+"<br>");
        }else{
            $('#answers').append("<input type='radio' name='ansa' value='A'>"+questionList[actualQuestionIndex].ansa+"<br>");
            $('#answers').append("<input type='radio' name='ansb' value='B'>"+questionList[actualQuestionIndex].ansb+"<br>");
            $('#answers').append("<input type='radio' name='ansc' value='C'>"+questionList[actualQuestionIndex].ansc+"<br>");
            $('#answers').append("<input type='radio' name='ansd' value='D'>"+questionList[actualQuestionIndex].ansd+"<br>");
        }
        delete map[actualQuestionIndex];
    }
</script>

【问题讨论】:

  • 查看您的 Javascript 我看不到任何会导致页面重新加载的内容,并且编辑 DOM 元素不会直接导致页面重新加载。您能否提供与此 Javascript 相关的 HTML?
  • 根据您的代码sn-p,您的页面无法重新加载。你可能做错了什么

标签: javascript jquery html ajax spring-mvc


【解决方案1】:

我相信这是按钮点击传播。试试这个:

$('#nextButton').click(function(event){
                event.stopPropagation()
                prepareQuestion(map);
 });

参考请read this link about event propagation.

【讨论】:

    【解决方案2】:

    您可能有一个表单中的按钮。
    然后,当您单击它时,表单会将页面发回。
    因为post比较慢,所以会先加载json,再reload完成。

    如果您在 onclick 属性中定义了函数,则需要添加“return false;”。

    onclick="somefunction(); return false;"

    否则,event.stopPropagation() 是正确的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-09
      • 2021-06-26
      • 1970-01-01
      • 2016-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多