Kyl*_*-St 3 javascript python django jquery django-templates
试图在我的模板中使用内联jQuery,这样我以后可以在AJAX调用中使用django url标记.但我无法让javascript工作.在我的子页面中,我扩展了我的索引页面,其中包含我的所有javascript和jQuery库.
{% extends "subpage.django" %}
{% block content %}
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script>
$("#dialog").hide();
$(".delete").click(function(){
alert("clicked!");
});
</script>
{% if graph %}
<h3> {{ graph.name }} </h3>
{% url 'graphImage' graph.id as the_graph %}
<img src="{{the_graph}}" alt="{{the_graph}}"/>
<a class="button delete" id="{{ graph.id }}" href="#">Delete</a>
<div id="dialog" title="Confirm delete">Are you sure?</div>
{% endif %}
{# need to add object.id to dialog in javascript #}
{% endblock %}
Run Code Online (Sandbox Code Playgroud)
做了一些编辑.将脚本放在块内容中,以便在显示源代码时显示.然而,仍然没有工作.我现在使用谷歌apis包含jQuery源代码.但内联脚本仍然无法正常工作.奇怪的是,如果我在控制台中输入它,那就完全没有了!我知道我错过了什么!
好吧,所以我解决了!我的第一个问题是由用户Paul Tomblin解决的(抱歉,我不知道如何添加你,我没有足够的代表来支持你的评论).我没有意识到我的子页面不会包含jQuery.出于某种原因,我认为它会继承这一点,但在这种情况下Django不会那样工作.
其次,我没有添加$(document).ready(function(){}); 因此,当页面加载时,它不会"运行"或"初始化"脚本.一旦文档准备好运行JavaScript,就会运行文档就绪函数,如下所示:http: //learn.jquery.com/using-jquery-core/document-ready/
这是我更新的代码:
{% extends "subpage.django" %}
{# once jQuery works, can do deleteGraph ajax requests #}
{% block content %}
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script type='text/javascript'>
$(document).ready(function(){
$("#dialog").hide();
$(".delete").click(function(){
alert("clicked!");
});
});
</script>
{% if graph %}
<h3> {{ graph.name }} </h3>
{% url 'graphImage' graph.id as the_graph %}
<img src="{{the_graph}}" alt="{{the_graph}}"/>
<a class="button delete" id="{{ graph.id }}" href="#">Delete</a>
<div id="dialog" title="Confirm delete">Are you sure?</div>
{% endif %}
{# need to add object.id to dialog in javascript #}
{% endblock %}
Run Code Online (Sandbox Code Playgroud)