[英]How to loop through a group of divs one by one on each click in jQuery?
I'm trying to output the text of each span, one by one, within the respective group, every time I click its parent button. 每当我单击其父级按钮时,我都试图在各个组中逐个输出每个跨度的文本。
I've tried different codes, but none of them worked for me. 我尝试了不同的代码,但是没有一个对我有用。 So, this is what I've been working on.
所以,这就是我一直在努力的。 http://jsfiddle.net/b6wfeaxz/2/
http://jsfiddle.net/b6wfeaxz/2/
js / jQuery js / jQuery
$( ".button" ).on( "click", function(){
$this = $(this);
$this.find( '.letter' ).each(function() {
$('.result').text($this.find('.letter').text());
});
});
HTML5 HTML5
<div class="result">A</div>
<div class="keypad">
<div class="button">
<div class="num">1</div>
<span class="letter">A</span>
<span class="letter">B</span>
<span class="letter">C</span>
</div>
<div class="button">
<div class="num">2</div>
<span class="letter">D</span>
<span class="letter">E</span>
<span class="letter">F</span>
</div>
<div class="button">
<div class="num">3</div>
<span class="letter">G</span>
<span class="letter">H</span>
<span class="letter">I</span>
</div>
</div>
Basically, I expect this to go back and forth with every click within the same button. 基本上,我希望每次单击同一按钮时都可以进行此操作。 In other words, I need this to work the same as a telephone keypad function, but the actual output is all three letters at once.
换句话说,我需要此功能与电话键盘功能相同,但是实际输出一次是全部三个字母。
Here's the fix, I realise this may not be the tidiest solution so feel free to edit: 解决方法如下,我意识到这可能不是最整洁的解决方案,因此请随时进行编辑:
var index = 0;
var direction = 1;
$(".button").on("click", function () {
var $this = $(this);
if ($this.hasClass("selected")) {
if (index >= $this.find(".letter").length - 1) {
direction *= -1;
} else if (direction == -1 && index == 0) {
direction *= -1;
}
index += direction;
} else {
$(".button").removeClass("selected");
$this.addClass("selected");
index = 0;
}
var result = $(this).children(".letter").eq(index).text();
$(".result").text(result);
});
http://jsfiddle.net/cndaeh7q/6/ http://jsfiddle.net/cndaeh7q/6/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.