who*_*rth 4 javascript django django-templates
我在 django 中有一个名为的模板,base.html它通过{% include 'gui/page.html' %}
在该模板中,我有以下 JavaScript,它允许在设置时选择整个文本字段,例如<p>This text I will select all</p>
<script>
$(document).ready(function(){
$('p').dblclick(function(e){
$(this).selectText();
e.preventDefault();
});
});
jQuery.fn.selectText = function(){
this.find('input').each(function() {
if($(this).prev().length == 0 || !$(this).prev().hasClass('p_copy')) {
$('<p class="p_copy" style="position: absolute; z-index: -1;"></p>').insertBefore($(this));
}
$(this).prev().html($(this).val());
});
var doc = document;
var element = this[0];
console.log(this, element);
if (doc.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
};
</script>
Run Code Online (Sandbox Code Playgroud)
如果我直接访问模板 @ http://localhost/gui/page.htmljavascript 就可以工作,但是如果我通过http://localhost/base.html双击该字段来访问它则什么也不做。
我已经尝试将 javascript 包含在 base.html 中,但它仍然无法加载。通过包含的模板调用时,django 如何加载 javascript?
刚刚有同样的问题。为了解决这个问题,需要做接下来的事情:
在base.html中添加:
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
{% block extrascripts %}{% endblock %}
将您的手工脚本放入/static/js/hand_made.js
在child模板中,其中包含,即我们使用的模板{% include 'child_template.html' %}:
{% load staticfiles %}{% block extrascripts %}<script type="text/JavaScript" src="{% static 'js/hand_made.js' %}"></script>{% endblock %}(由于某种原因无法添加漂亮的样式)。
如果由于某些原因需要从模板向 JS 提供数据,则需要执行以下操作:
{% block extrascripts %}
<script>
var my_var_1 = "{{ some_template_data.var_1 }}",
my_var_2 = "{{ some_template_data.var_12 }}";
</script>
<script type="text/JavaScript" src="{% static 'js/hand_made.js' %}"></script>
{% endblock %}
Run Code Online (Sandbox Code Playgroud)
在这种情况下my_var_1,my_var_2将在hand_made.js
| 归档时间: |
|
| 查看次数: |
9570 次 |
| 最近记录: |