1

我比 jQuery 更熟悉 JS,但看起来我需要扩展我对后者的了解才能实现我想要做的事情。

我有这个代码:它有一个在黑色、绿色和红色之间切换的按钮,并且分别不选中框、框 1 或框 2。

JS中的示例:JS 演示

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) 
})

谢谢你的帮助!

4

2 回答 2

0

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

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);
    }
});
于 2013-03-30T17:30:22.173 回答
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 元素的依赖较少,并支持任意数量的复选框和双向更新。

于 2013-03-30T17:55:31.293 回答