[英]JQuery / Javascript selector loop through array of elements with toggle() or add/removeClass()
I have: 我有:
<button id="1"> Button 1 </button>
<span id="s1"> Span 1 </span>
<button id="2"> Button 2 </button>
<span id="s2"> Span 2 </span>
<button id="3"> Button 3 </button>
<span id="s3"> Span 3 </span>
What I need is: 我需要的是:
-When click button 1, span 1 shows and when click again it disappears and shows the button 1. -When click button 2, span 2 shows and when click again it disappears and shows the button 2. -When click button 3, span 3 shows and when click again it disappears and shows the button 3. - 当单击按钮1时,跨度1显示,当再次单击时,它会消失并显示按钮1. - 单击按钮2,跨度2显示,再次单击时消失并显示按钮2. - 单击按钮3,跨度3显示,再次点击它会消失并显示按钮3。
I currently have a loop creating the html, assigning ids in an array and set to a class (.off) with display: none by default. 我目前有一个创建html的循环,在一个数组中指定id并设置为一个类(.off),默认情况下为display:none。 For example:
例如:
$.(body).append( '<button id="'+[i]+'">Button'+[i]+'</button>
<span id="'+[i]+'" class="off">'
But I am having trouble selecting one by one. 但我无法逐一选择。 I get errors like, either only the first element works, or I click on 1 button and shows all the spans at the same time.
我得到错误,或者只是第一个元素工作,或者我点击1个按钮并同时显示所有跨度。 My code:
我的代码:
for ( var j = 0; j < id.length; j++ ){
$('button' ).on("click", function(e) {
$('span' ).removeClass('off').addClass('on');
$(this).on("click", function(e) {
$('span').removeClass('on').addClass('off');
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.