簡體   English   中英

jQuery On單擊時不會觸發

[英]jQuery On click wont fire

我有一個textbox ,一個復選框和一個span標記。 當我單擊復選框時,它應該在span標簽中顯示其狀態。 更新textbox ,它將重新插入復選框塊。 現在單擊復選框時,它無法更新狀態。

我正在為復選框click事件使用on事件處理程序,因此我希望它能正常工作。

知道為什么它不能按預期工作嗎?

 $('div[role] input[type=checkbox]').on('click', chg); $('div[role] input[type=text]').on('input', sourceChanged); function chg() { var istiki = $(this).is(":checked"); $('#upd').html(istiki); } function sourceChanged() { $('span', $(this).closest('.input-group')).html('<input type="checkbox">'); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div role="Tiki" class="input-group"> <input type="text" class="form-control" /> <span class="input-group-addon"><input type="checkbox" /></span> </div> <span id="upd"></span> 

當值更改時動態創建新復選框時,需要通過將事件分配給非動態祖先來將事件委托給復選框:

$('div[role]').on('change', 'input[type=checkbox]', chg);

請注意我是如何使用change而不是click因為這更適合復選框。


在下面的代碼段中,我還將$(this).is(":checked")更改為this.checked

 $('div[role]').on('change', 'input[type=checkbox]', chg); $('div[role] input[type=text]').on('input', sourceChanged); function chg() { var istiki = this.checked; $('#upd').html(istiki); } function sourceChanged() { $('span', $(this).closest('.input-group')).html('<input type="checkbox">'); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div role="Tiki" class="input-group"> <input type="text" class="form-control" /> <span class="input-group-addon"><input type="checkbox" /></span> </div> <span id="upd"></span> 

還請注意,如果您想讓它說為false ,則應將istiki變量轉換為字符串:

$('#upd').html('' + isticki);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM