javascript - 带有 data-ui 标签的复选框和单选按钮的悬停功能

标签 javascript jquery html css checkbox

我有一个非常简单的任务:

  • 创建查找带有 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-radiobuttonfind() 另一方面是完全不同的 - 它找到一个 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/

相关文章:

JQuery 同位素插件神秘错误

javascript - jQuery 对象 html() 不起作用...但innerHtml 起作用

jquery - 搜索框和附加按钮未在导航栏中对齐

c# - 文本框自动完成

javascript - 如何使用innerHTML 在 javascript 中添加 svg html 树?

php - 使用ajax和php在MYSQL中插入数据

jquery - 如何在 jQuery 中访问模型属性

javascript - Highcharts - Highstock "inputEditDataFormat"中断输入

javascript - 用于 HTTP 基本身份验证的纯 JavaScript 代码?

jquery - 表单内的两个按钮