JQuery 获取复选框 ID
JQuery get checkbox id
我正在尝试获取复选框的 id
。
页面上有几个复选框有 id
,例如:channel_left_restream_ids_42
、channel_left_restream_ids_44
等。我需要在选中其中一个时处理事件并获得 id
的检查。
所以对于代码为 <input type="checkbox" value="42" checked="checked" name="channel[left_restream_ids][]" id="channel_left_restream_ids_42">
的复选框和这样的 coffescript:
$("input[id*=channel_left_restream_ids]").change (e) =>
alert($(this).attr("id"))
我无法让它工作。它说 undefined
。我尝试了很多替代方案,none 奏效了。我哪里做错了?
希望我能正确理解您的问题,但我希望这可以将您推向正确的方向:
要知道这个特定的复选框是否被选中,您必须使用它的确切 ID。
因此,在您的脚本中您正在寻找此 ID:
id*=channel_left_restream_ids
但是复选框的id是"channel_left_restream_ids_42"
我不知道您正在使用的代码,但可能有很多 "channel_left_restream_ids",或者该 id 可能用于其他非复选框的内容。
所以这值得一试:
[id*=channel_left_restream_ids_42]
在你的 jfiddle 中,我给每个复选框一个 class 名称 getId 并使用了这个代码。
这应该会让您朝着正确的方向前进。
$(".getId").each(function(){
$(this).on("change", function(){
var id = $(this).attr("id");
console.log(id);
});
});
如果复选框都具有相同的名称,您也可以使用它。
没想到问题出在jQuery之类的。
那只是我咖啡中粗体数组的问题。
将 $("input[id*=channel_left_restream_ids]").change (e) =>
替换为 $("input[id*=channel_left_restream_ids]").change (e) ->
(区别仅在于行尾的数组)就可以了。
我正在尝试获取复选框的 id
。
页面上有几个复选框有 id
,例如:channel_left_restream_ids_42
、channel_left_restream_ids_44
等。我需要在选中其中一个时处理事件并获得 id
的检查。
所以对于代码为 <input type="checkbox" value="42" checked="checked" name="channel[left_restream_ids][]" id="channel_left_restream_ids_42">
的复选框和这样的 coffescript:
$("input[id*=channel_left_restream_ids]").change (e) =>
alert($(this).attr("id"))
我无法让它工作。它说 undefined
。我尝试了很多替代方案,none 奏效了。我哪里做错了?
希望我能正确理解您的问题,但我希望这可以将您推向正确的方向:
要知道这个特定的复选框是否被选中,您必须使用它的确切 ID。
因此,在您的脚本中您正在寻找此 ID: id*=channel_left_restream_ids
但是复选框的id是"channel_left_restream_ids_42"
我不知道您正在使用的代码,但可能有很多 "channel_left_restream_ids",或者该 id 可能用于其他非复选框的内容。
所以这值得一试: [id*=channel_left_restream_ids_42]
在你的 jfiddle 中,我给每个复选框一个 class 名称 getId 并使用了这个代码。
这应该会让您朝着正确的方向前进。
$(".getId").each(function(){
$(this).on("change", function(){
var id = $(this).attr("id");
console.log(id);
});
});
如果复选框都具有相同的名称,您也可以使用它。
没想到问题出在jQuery之类的。
那只是我咖啡中粗体数组的问题。
将 $("input[id*=channel_left_restream_ids]").change (e) =>
替换为 $("input[id*=channel_left_restream_ids]").change (e) ->
(区别仅在于行尾的数组)就可以了。