我有很多表格,當一個複選框被選中時 - 所有其他表格都應該清除。您可以檢查此表中任意數量的複選框,但一次只能查看一個表格中的複選框。 我會如何去做這件事?如果可能的話,我想避免使用ID,因爲我有8個表。如果選中表格複選框,取消選中其他表格複選框?
$('input[type=checkbox]').on('click', function() {
});
我有很多表格,當一個複選框被選中時 - 所有其他表格都應該清除。您可以檢查此表中任意數量的複選框,但一次只能查看一個表格中的複選框。 我會如何去做這件事?如果可能的話,我想避免使用ID,因爲我有8個表。如果選中表格複選框,取消選中其他表格複選框?
$('input[type=checkbox]').on('click', function() {
});
您可以:
$(this).closest("table")
$("table").not($table)
... .prop("checked", false)
。這應該給一些像這樣的代碼:
$('input[type=checkbox]').on('click', function() {
var $table = $(this).closest("table"); // Current table
$("table").not($table) // Other tables
.find("input[type=checkbox]:checked") // Checked input of these tables
.prop("checked", false); // Uncheck them
});
看到這個小提琴:http://jsfiddle.net/69o3e5y4/2/
此外,對於每個選中的複選框,我們可以記錄.closest('td')。next()。html()名字?所以如果只有一個被選中,「紅色」,但如果多於一個添加逗號「紅色,藍色」,最後一個詞不應該有逗號「紅色,藍色」。 – triplethreat77 2014-09-23 17:29:47
明白了。 $('input [type = checkbox]')。on('click',function(){ var $ table = $(this).closest(「table」); $(「table」)。not($ ('checkbox':checked')。prop(「checked」,false); var chklist =「」; $('input [type = checkbox]:checked')。each (函數(){ var sThisVal =(this.checked?「1」:「0」); chklist + =(chklist ==「」?sThisVal:「,」+ sThisVal); }); console。 log(chklist); }); – triplethreat77 2014-09-23 17:40:21
我沒有試過,但我會用類。因此,Table1中的所有複選框都將是「Table1」類,Table2中的所有複選框都將放在「Table2」類中,等等。
然後,在事件處理程序中,您可以遍歷頁面上的每個複選框,如果他們的課程與點擊的課程不匹配,則取消選中所有課程。
比如(再次提示,未測試):
$("input[type=checkbox]").click(function() {
if ($(this).prop("checked") == true){
var CurrentClass = $(this).prop("class");
$("input[type=checkbox]").each(function() {
if ($(this).prop("class") != CurrentClass)
$(this).prop("checked", false);
});
}
});
這個jQuery工作沒有任何標識:
$('table').each(function(index){
$(this).find('input').each(function()
{
$(this).on('click', function() {
clearThisTablesCheckboxes(index);
});
});
});
function clearThisTablesCheckboxes(position){
$('table').each(function(index){
$(this).find('input').each(function()
{
if(position != index)
{
var prop=false;
$(this).prop('checked',prop);
}
});
});
}
這聽起來像單選按鈕會爲這個完美的。有沒有原因,你不想使用它們呢? – Michael 2014-09-23 17:14:47
@microsby0:「你可以在這張表中檢查任意數量的複選框」 – 2014-09-23 17:15:30
@DarkFalcon啊謝謝,我沒有注意到那部分。你可以使用班級,每個班級一個班級?它比ids好一點 – Michael 2014-09-23 17:16:45