[英]Javascript and django app / boilerplate integration
我正在编写Django应用程序,并结合样板模板。 我有一个带有复选框的表,我正在尝试使用JavaScript来实现“全选”复选框,但无法正常工作
在此建议django复选框之后,我在main.js中放入的jQuery全选
$("#selectAll").live('change',function() {
$(".checkbox_delete:checkbox").attr('checked', this.checked);
});
我还尝试将其直接放在index.html上
在我的index.html上,您写道
<input type="checkbox" id="selectAll" />
<label for="selectAll"> Select</label>
{% for event in latest_events_list %}
<input type="checkbox" class="checkbox_delete" name="event" id="event.id"
value="{{ event.id }}" />
{% endfor %}
该页面已正确显示,但javascript无法正常工作
样板生成指向js文件的链接。 在标题中出现
<script src="/static/js/dh5bp/vendor/modernizr-2.6.2.min.js"></script>
在关闭body标签之前:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>window.jQuery || document.write ('<script src="/static/js/dh5bp/vendor/jquery-1.10.2.min.js"><\/script>')</script>
<script src="/static/js/dh5bp/plugins.js"></script>
<script src="/static/js/main.js"></script>
所有js文件均已正确链接,我可以关注它们
我没有js的经验,所以不知道是否缺少任何东西。
编辑:
我在两个浏览器上都安装了萤火虫。 在Firefox上,它警告我
TypeError: $(...).live is not a function
$("#selectAll").live('change',function() {
所以我更改了代码
$(function(){
$("#selectAll").change(function() {
$(".checkbox_delete:checkbox").attr('checked', this.checked);
});
});
现在它仅在我第一次加载页面时起作用,但是如果我“全选”和“取消全选”,我将无法再次“全选”它们
$(".checkbox_delete:checkbox").attr('checked', $(this).attr('checked));
试试这个
终于成功了
问题是attr()
根据这篇文章, jQuery选择所有复选框
在jQuery 1.6及更高版本中,应将prop()用于“已检查”状态,而不是通过传递true或false的attr()
最后,工作代码是
$("#selectAll").change(function() {
$(".checkbox_delete:checkbox").prop('checked', this.checked);
});
在我的代码中,唯一可以发现的错误是:
$(".checkbox_delete:checkbox").attr('checked', this.checked);
这应该是
$(".checkbox_delete[type="checkbox"]").attr('checked', this.checked);
注意
如果您有很好的类名并且在收音机等上不使用.checkbox_delete
,则不需要[type="checkbox"]
。
您原来的选择器无效。 您将有错误登录到控制台。
在firefox中,此快捷方式是F12
,如果您没有安装FF / Chrome的firebug,我建议您这样做,因为它是检查JS错误的极好方法,通常也可以解决它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.