我有一个非常简单的任务:
- 创建查找带有 data-ui 标签的复选框或单选按钮的函数
- 使用鼠标悬停和鼠标移开事件绑定(bind)到复选框或单选按钮的标签
- 在标签悬停时添加类并通过标签悬停移除类
这是我的代码
var HoverRadioCheck = {
init: function() {
this.findRadioCheckInput();
this.bindToLabel();
},
findRadioCheckInput: function() {
$("input[type='radio'], input[type='checkbox']").find.dataAttr('ui-checkbox', 'ui-radiobutton');
},
bindToLabel: function() {
$("input[type='radio'], input[type='checkbox'] + label").bind( "mouseenter mouseleave", function() {
$( this ).toggleClass( "entered" );
});
}
};
HoverRadioCheck.init();
<div class="form-group">
<input name="checkbox_test_2" id="checkbox_test_2_1" class="checkbox" type="checkbox" data-ui-checkbox/>
<label for="checkbox_test_2_1">Bacon ipsum dolor amet salami andouille corned beef</label>
</div>
<div class="form-group">
<input name="radiobutton_test_1" id="radiobutton_test_1_1" class="radiobutton" type="radio" data-ui-radiobutton/>
<label for="radiobutton_test_1_1">Lorem Ipsum</label>
</div>
任何帮助将不胜感激
最佳答案
现在很清楚了,你做的很好,但变化不大,让我解释一下:
1) 没有名为 item.find.dataAttr
甚至 item.dataAttr
的 JQuery 函数,它应该是 item.data('ui-复选框')
或 item.attr('data-ui-checkbox')
无效:
$("input[type='radio']").find.dataAttr('ui-radiobutton');
$("input[type='radio']").dataAttr('ui-radiobutton');
有效:
$("input[type='radio']").attr('data-ui-radiobutton');
$("input[type='radio']").data('ui-radiobutton');
基本上 attr()
函数会查找元素中的任何属性,因此您必须给出属性的完整名称,但另一方面 data()
函数看起来仅用于 data-
属性,因此在这种情况下,您只需在 data-
之后提供名称,比如 ui-radiobutton
。 find()
另一方面是完全不同的 - 它找到一个 ELEMENT 而不是一个属性,所以基本上根据您的要求,您甚至不需要它。使用 find()
的示例可能是:
$('.form-group').find('input[type='radio']');//这会给你 radio 元素
2) 这很简单,您的 bindToLabel
函数很好,只是您甚至需要为第一个参数提供 + label
。你的不是无效的,但它不会绑定(bind)单选按钮的标签,但会绑定(bind)单选按钮本身。我想你不想要那个。所以应该是:
$("input[type='radio'] + label, input[type='checkbox'] + label").bind(
所以你最终的 JQuery 应该看起来像 - Codepen here
var HoverRadioCheck = {
init: function() {
this.findRadioCheckInput();
this.bindToLabel();
},
findRadioCheckInput: function() {
$("input[type='radio'], input[type='checkbox']").data('ui-checkbox', 'ui-radiobutton');
},
bindToLabel: function() {
$("input[type='radio'] + label, input[type='checkbox'] + label").bind( "mouseenter mouseleave", function() {
$( this ).toggleClass( "entered" );
});
}
};
HoverRadioCheck.init();
关于javascript - 带有 data-ui 标签的复选框和单选按钮的悬停功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40242737/