今天在開發(fā)中,遇到一件事,沒做過多測試
網(wǎng)上搜索的jquery將checkbox改為選中狀態(tài),是如下方法:
$(this).attr('checked',true);
form.render('checkbox');
但是實際情況中,上述方法 雖會將html的checked變成選中,但是更新渲染時無效,因此在這記下這一點。使用如下方法將checkbox置為選中狀態(tài)時再去更新渲染,此方法有效。
$(this).prop('checked',true);
form.render('checkbox');
寫完文章后,因為不是專門做前端,所以查了查attr()和prop()的區(qū)別
從 jQuery 1.6 開始新增了一個方法 prop()。
從中文意思看,兩者分別是獲取/設(shè)置 attributes 和 properties 的方法,那么為什么還要增加 prop() 方法呢?
Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior.
因為在 jQuery 1.6 之前,使用 attr() 有時候會出現(xiàn)不一致的行為。
那么,什么時候使用attr(),什么時候使用prop()?
To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.
根據(jù)官方的建議:具有 true 和 false 兩個屬性的屬性,如 checked, selected 或者 disabled 使用prop(),其他的使用 attr()