[英]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.