Django jQuery无法正常工作?
这就是我的模板:
{% extends 'typer/base.html' %} {% load url from future %} {% load staticfiles %} {% block title %}{{ p_name }}{% endblock %} {% block body_block %} $('#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()); } }); {{ p_name }}
This passage is {{ p_wlength }} words, {{ p_clength }} characters long.
{% if passage %} {{ p_text_body|linebreaksbr }}
{% else %} The specified text {{ p_name }} does not exist! {% endif %} Begin typing to start the test.
{% endblock %}
我想做的就是在控制台上打印一条消息,检查该function是否正常。 我对它不起作用感到困惑的原因是我可以在http://jsfiddle.net/d8c4z300/上完全运行它。 那么为什么消息打印在那里但不是在我运行django模板时?
你需要$(function(){ ... })
(或$( document ).ready(function() { ... });
这是相同的,只是更长)围绕你的js代码:
所以:
$(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()); } }); });
小提琴正在工作,因为你将它设置为onload
,这几乎等于$(function(){ ... })
。