如何在循环内的元素类之间切换?

时间:2017-03-03 14:47:54

标签: javascript jquery

单击按钮时,我试图在循环内的元素类之间切换。以下是我认为将要起作用的样本。

https://jsfiddle.net/WPederzoli/ts5tm4h6/

$(function()    {
    $('button').on('click', function() {
    for (i = 0; i < 10; i++) {
        $('p.firstClass').toggleClass('secondClass');
    }
  });   
});

3 个答案:

答案 0 :(得分:2)

不需要任何循环来切换类。也就是你在类name.class名称的错误是fistClass而不是firstClass

$(function()	{
	$('button').on('click', function() {

    	$('p.fistClass').toggleClass('secondClass');
    
  });	
});
.fistClass {
  color:red;
}
.secondClass {
  color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="fistClass">
Some text!
</p>
<button type="button">
Click Me!
</button>

答案 1 :(得分:1)

解决您问题的一个非常简单的方法。首先,您需要为Fiddle添加Jquery。 (单击Javascript)然后将“拳头”更改为“第一个”。最后删除循环。

https://jsfiddle.net/Nhawdge/qwo2cvkb/

^H2^H^A^Hpr@deep^H
^H4^H^A^HP¦âdéëp^H
^H1^H^A^Hdeep^H
^H3^H^A^Hprádeep^H

JavaScript的:

HTML: 
<body>
<p class="firstClass">
Some text!
</p>
<button type="button">
Click Me!
</button>
</body>

答案 2 :(得分:0)

它无效,因为Option Explicit Sub ChkAfternoonAssignmentsV2() Dim dayToChk As Variant Dim i As Variant Dim r As Range Dim p As Variant Do While r Is Nothing dayToChk = InputBox("Which day (use 3-letter abbreviation) would you like to check afternoon assignments?") Select Case dayToChk Case "Mon", "Tue", "Wed", "Thu", "Fri" Set r = ActiveSheet.Range(dayToChk & "Aft_MA_Slots") Case Else MsgBox "'dayToChk & " ' is not in the expected format. Try Mon, Tue, Wed, Thu, or Fri." End Select Loop Dim AckTime As Integer, InfoBox As Object Set InfoBox = CreateObject("WScript.Shell") AckTime = 1 Select Case InfoBox.Popup("Checking MA Assignments", AckTime, "Checking MA Assignments", 0) Case 1, -1 End Select Dim notFounds As String, duplicates As String For Each i In Sheets("Control").Range("MA_List") If WorksheetFunction.CountIf(r, i) < 1 Then If i <> "OOO" Then notFounds = notFounds & i.Value & vbLf ElseIf WorksheetFunction.CountIf(r, i) > 1 Then If i <> "OOO" Then duplicates = duplicates & i.Value & vbLf End If Next i If notFounds <> "" Then MsgBox "these items have not been found: " & vbCrLf & vbCrLf & notFounds If duplicates <> "" Then MsgBox "these items have duplicates: " & vbCrLf & vbCrLf & duplicates End Sub 的样式覆盖了.firstClass的样式,我会做类似的事情

.secondClass
$(function() {
  $('button').on('click', function() {
    $('p.toggleMe').toggleClass('secondClass');
  });
});
p {
  color: red;
}

.secondClass {
  color: blue;
}