我有以下表单代码:
<input data-color="orange" id="vote_color_id_2" name="color" type="radio" value="2" />Orange
<input data-color="blue" id="vote_color_id_3" name="color" type="radio" value="3" />Blue
<input data-color="green" id="vote_color_id_4" name="color" type="radio" value="4" />Green
我在 Rails 中使用 Coffee 脚本,现在我只是想提醒数据属性 data-color
的值。
这是我的 CoffeeScript
jQuery ->
$("input[name='color']").change ->
color = this.data()
alert color.color
编译后的 jQuery 如下所示:
(function() {
jQuery(function() {
return $("input[name='color']").change(function() {
var color;
color = this.data();
return alert(color.color);
});
});
}).call(this);
但我一直收到此错误?
Uncaught TypeError: Object #<HTMLInputElement> has no method 'data'
最佳答案
jQuery ->
$("input[name='color']").change ->
color = $(this).data()
alert color.color
jQuery 将 this
分配给触发回调的元素,但它从来不是 jQuery 对象。所以如果你想调用它的 jQuery 方法,你必须包装它。
关于jquery - jQuery/Coffee 脚本中的数据属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9492168/