添加/删除属性仅在循环中第一次工作

时间:2014-03-18 15:12:12

标签: jquery css

我正在尝试循环一些单选按钮,一次检查一个,但不幸的是,CSS :checked css选择器只能在第一次我这样做?!

查看我正在谈论的内容的最简单方法是以下示例:

http://codepen.io/EightArmsHQ/pen/2b490930b4a2b4e33d5c1e734f05302d

如何让它循环,让CSS选择器一直工作?我在Chrome中看到它,所以它可能是Chrome漏洞,或者更可能是我在某处做错了什么..

有些图片:

第一次(黑点是使用:checked + span选择的范围,数字是应该检查的数组索引):

http://snag.gy/53qaL.jpg

第二次:

enter image description here

如果你检查元素,你会看到框正在检查。

HTML:

<div id="notes">
  <input class="clap" type="radio" name="note" /><span></span>
  <input class="clap" type="radio" name="note" /><span></span>
  <input class="clap" type="radio" name="note" /><span></span>
  <input type="radio" name="note" /><span></span>
  <input class="clap" type="radio" name="note" /><span></span>
  <input class="clap" type="radio" name="note" /><span></span>
  <input type="radio" name="notes" /><span></span>
  <input class="clap" type="radio" name="notes" /><span></span>
  <input type="radio" name="note" /><span></span>
  <input class="clap" type="radio" name="note" /><span></span>
  <input class="clap" type="radio" name="note" /><span></span>
  <input type="radio" name="note" /><span></span>
</div>
<p>
  <span id="output"></span>
</p>

CSS:

$borderWidth: 2px;

body{
  text-align:center;
  font-family: 'Hammersmith One', sans-serif;
}

#notes{
  padding:2em 0;
}

p{
  margin:2em 0;
}

input{
  display:none;
}
input + span{
  border-radius:400px;
  border:$borderWidth solid black;
  background:white;
  display:inline-block;
  margin:10px;
  width: 10px;
  height: 10px;
  position:relative;
  &:after{
    content:'';
    position:absolute;
    top:20px;
    left:-$borderWidth;
    border-radius:400px;
    border:2px solid black;
    background:white;
    display:inline-block;
    width: 10px;
    height: 10px;
    position:relative;
  }
}

input.clap + span{
  background:#16ab68;
  &:after{
    background:#16ab68;
  }
}

input:checked + span{
  background:#000;
  &:after{
    background:#000;
  }
}

JS:

var bpm = 130;
var intervalGap = 60000 / bpm;
var tick = true;

var phraseLength = 12;
var current = phraseLength - 1;

setInterval(function(){  
  current += 1;
  if(current >= phraseLength){
    current = 0;
  }

  $("#notes input").removeAttr("checked");

  var currentInput = $("#notes input")[current];

  $(currentInput).attr("checked","true");

  $("#output").html(current);

},intervalGap);

2 个答案:

答案 0 :(得分:4)

使用prop修复问题,.prop()而不是.attr()

$(currentInput).prop("checked",true);

DEMO

答案 1 :(得分:0)

以下是修复 - http://jsfiddle.net/Cg7z8/

改变 -

  $(currentInput).attr("checked","true");

  $(currentInput).prop("checked","true");

使用jQuery .1.10.0

在FF中测试