【问题标题】:Django jQuery not working?Django jQuery 不工作?
【发布时间】:2015-01-01 10:48:23
【问题描述】:

这是我的模板的样子:

{% extends 'typer/base.html' %}
{% load url from future %}

{% load staticfiles %}

{% block title %}{{ p_name }}{% endblock %}

{% block body_block %}
<script type='text/javascript'
src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<script>
    $('#user_passage_text').on('keyup', function(e) {
        if ( e.which === 13 ) {
        var time = (new Date()).getTime() - $(this).data('time');
        $(this).data('time', 0);
        console.log('Time passed : ' + time + ' milliseconds');

        }else if ( !$(this).data('time') ){
            $(this).data('time', (new Date()).getTime());
        }
    });
</script>

    <h1>{{ p_name }}</h1>
    <p>This passage is {{ p_wlength }} words, {{ p_clength }} characters long.</p>
    {% if passage %}
        <p><blockquote>{{ p_text_body|linebreaksbr }}</blockquote></p>

    {% else %}
        The specified text {{ p_name }} does not exist!
    {% endif %}

    <p>
        Begin typing to start the test.
    </p>
    <textarea id="user_passage_text"></textarea>


{% endblock %}

我想要做的就是向控制台打印一条消息以检查该功能是否正常工作。我对它不起作用感到困惑的原因是我可以在http://jsfiddle.net/d8c4z300/ 上完美运行它。那么为什么在我运行 django 模板时会打印出消息而没有打印出来呢?

【问题讨论】:

  • 您的浏览器中是否有任何错误消息?出来的 html 长什么样子?
  • 没有任何错误信息。即将发布的 html 如下所示:pastebin.com/hm1Ty7Lu.

标签: javascript jquery python django


【解决方案1】:

你的 js 代码周围需要$(function(){ ... })(或$( document ).ready(function() { ... });,只是更长):

所以:

$(function(){

  $('#user_passage_text').on('keyup', function(e) {
    if ( e.which === 13 ) {
    var time = (new Date()).getTime() - $(this).data('time');
    $(this).data('time', 0);
    console.log('Time passed : ' + time + ' milliseconds');

    }else if ( !$(this).data('time') ){
        $(this).data('time', (new Date()).getTime());
    }
  });

});

fiddle 正在工作,因为您将其设置为onload,这几乎等于此处的$(function(){ ... })

【讨论】:

    猜你喜欢
    • 2014-08-09
    • 2018-06-18
    • 1970-01-01
    • 2019-10-18
    • 2013-06-30
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 2019-10-31
    相关资源
    最近更新 更多