将特定的JS转换为通用的jQuery脚本(示例)

时间:2013-03-30 17:06:31

标签: javascript jquery button checkbox

我比JS更熟悉JS,但看起来我需要扩展后者的知识才能实现我想要的目标。

我有这样的代码:它有一个在黑色,绿色和红色之间切换的按钮,分别不检查box,box1或box2。

JS中的示例:JS demo

var colors = ["green", "red", "black"];

function setColor(el) {
   el.colorIdx = el.colorIdx || 0;
   el.style.color = colors[el.colorIdx++ % colors.length];
document.getElementById('box1').checked = el.style.color == 'green';
document.getElementById('box2').checked = el.style.color == 'red';
}

但我需要使脚本更通用,以便它适用于任何按钮/复选框。这是我到目前为止所开始的,但我不知道如何将它与JS这样的颜色特性结合起来。

jQuery

$("input").on('click', function () {
    $("[name^=" + this.value + 1 + "]").attr('checked', true)
    $("[name^=" + this.value + 2 + "]").attr('checked', true) 
})

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

您不必使用jQuery来完成此任务。这是一个纯JS解决方案,我将您的复选框/按钮集包装在<div class="color-set">中,以便轻松地允许更多,然后使用data-color属性设置哪个颜色 index (可以很容易地检查文本)这是我们是否设置了复选框。

jsFiddle

<强> HTML

<div class="color-set">
    <input type="checkbox" data-color="0" />
    <input type="checkbox" data-color="1" />
    <input type="button" value="box" />
</div>

<强>的JavaScript

var colors = ["green", "red", "black"];

function setColor() {
    this.colorIdx = (this.colorIdx || 0) % colors.length;
    this.style.color = colors[this.colorIdx];

    for (var i = 0; i < this.checkboxes.length; i++) {
        this.checkboxes[i].checked = this.colorIdx == this.checkboxes[i].getAttribute('data-color');
    }

    this.colorIdx++;
}

window.addEventListener('load', function() {
    var colorSet = document.getElementsByClassName('color-set');

    for (var i = 0; i < colorSet.length; i++) {
        var button = colorSet[i].querySelector('input[type=button]');
        button.checkboxes = colorSet[i].querySelectorAll('input[type=checkbox]');
        button.addEventListener('click', setColor);
    }
});

答案 1 :(得分:0)

这是一个使用jQuery的更通用的选项:

内容:

<div class='example-container'>
    <input type="checkbox"  />
    <input type="checkbox"  />
    <input type="button"  value="box" />
</div>

代码:

function colorCycle(container, colors) {
  colors = colors || ["black", "green", "red"];
  var button = container.find(':button');
  var checkboxes = container.find(':checkbox');
  var index = 0;

  function setIndex(newIndex) {
    index = newIndex;
    checkboxes.attr('checked', false);
    if (index > 0)
      $(checkboxes[index - 1]).attr('checked', true)

    button.css('color', colors[index]);
  }

  button.click(function () {
    setIndex((index + 1) % (checkboxes.length + 1));
  });

  // Optional bidirectional support:
  checkboxes.change(function () {
    var checkbox = $(this);
    if (!checkbox.attr('checked')) {
      setIndex(0);
    } 
    else {
      setIndex(checkboxes.index(checkbox) + 1);
    }
  });
}

$(function () {
  colorCycle($('.example-container'));
});

http://jsfiddle.net/Lmyfr/

它对HTML元素的依赖性较小,并支持任意数量的复选框和双向更新。