2013-02-22 71 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