2013-02-22 73 views
0

我根本無法使用jQuery更新元素的屬性。在jQuery中無法更改屬性

HTML:

<input type="checkbox" name="row1" value="" > 

的jQuery:

$(document).ready(function (event) { 
    $("input[type='checkbox']").change(function (e) { 
     var name = $(this).attr('name'); 
     // grab name of original 
     var value = $(this).attr('value'); 
     // grab value of original 
     var ischecked = $(this).is(":checked"); 
     //check if checked 
     if (!ischecked) { 
      $('#' + name).removeAttr("checked"); 
      alert("removed attr "); 
     } else { 

      $('#' + name).attr("checked", "checked"); 
      alert($('#' + name).attr("checked")); 

     } 

    }); 
}); 

顯示一個警告 '未定義' 當我檢查。

+0

你能澄清究竟發生了什麼? – 2013-02-22 11:50:47

+1

# - 用於標識。你需要在jQuery選擇器中使用[name = yourname]來尋找名字 – 2013-02-22 11:52:08

+0

'$('#'+ name)'elem有這個ID嗎?你可以發佈或詳細說明嗎? – Jai 2013-02-22 11:52:24

回答

0

您的選擇是錯誤的。 您還沒有設置ID到複選框。它應該看起來像:

$("input[name='"+name+"']").removeAttr("checked"); 
2

變化$('#' + name)$(this)

$('#'+name).removeAttr("checked"); 

$(this).removeAttr("checked"); 

如果使用jQuery 1.6或更高版本,可以使用

$(this).prop("checked", false); 
+0

它是否也更新了html標籤屬性呢?我希望標籤屬性發生變化,因爲我有一定​​的依賴關係。我通過'attr'獲取屬性後面的代碼 – Nezam 2013-02-22 12:01:02

0

'#' 工程ID但不名稱

<input type="checkbox" name="row1" id="row1" value="" > 

或使用這個得到參考。

1

嘗試改變這種方式:check the jsbin

$(document).ready(function (event) { 
    $("input[type='checkbox']").change(function (e) { 
    var name = $(this).attr('name'); 
    var value = $(this).val(); 
    var ischecked = $(this).is(":checked"); 

    if (!ischecked) { 
     $(this).prop("checked", false); 
     alert("removed attr "); 
    } else { 
     $(this).prop("checked", true); 
     alert($(":checked").val()); 
    } 

    }); 
}); 

shows up an alert 'undefined' when i check.

這應該是因爲你是不是要檢查值,而不是you can check the length of the **$(':checked')**

alert($(":checked").length); 

,如果你嘗試檢查:

alert($(":checked")); 

您將得到警報[object object]

+0

是否也更新了html標籤屬性呢?我想標籤屬性改變,因爲我有一定​​的依賴性。我通過代碼後面的'attr'獲取屬性 – Nezam 2013-02-22 12:00:17

+0

看看你是否嘗試了這樣的東西,你可以隨時在你的代碼中改變attr。 – Jai 2013-02-22 12:04:12

+0

does' $(this).prop(「checked」,true);'translate into''給我一個是或不是 – Nezam 2013-02-22 12:07:14