It should be, You have used id
selector in HTML <span id="SpanHeader" class="CourseHeader">
$("#SpanHeader").toggleClass("Black");
instead of
$(".SpanHeader").toggleClass("Black");
题
I have a Span tag like so
<span id="SpanHeader" class="CourseHeader"><a class="SubCourses" href="#" ><strong>@course.CourseTitle</strong></a></span>
The Span is styled by a CSS class called CourseHeader. When the user clicks the hyperlink within the Span I would like the Span CSS class to toggle with another CSS class.
I have the following CSS elements
/********* Course Collaspable Headings ******/
.CourseHeader
{
background-color: #F5F5F5;
border: 1px solid black;
display: inline-block;
width: 600px;
padding: 4px;
color: Black;
}
.CourseHeader.Black
{
background-color: #000000;
border: 1px solid black;
display: inline-block;
width: 600px;
padding: 4px;
color: #FFFFFF;
}
And the following JQuery code to try and make the Span change style once the hyperlink is clicked
$("a.SubCourses").click(onSubCourses);
function onSubCourses() {
$(".SpanHeader").toggleClass("Black");
}
I've tried looking at how others have achieved this, like this however I can't get it working myself.
Could someone please help?
Thanks.
解决方案
It should be, You have used id
selector in HTML <span id="SpanHeader" class="CourseHeader">
$("#SpanHeader").toggleClass("Black");
instead of
$(".SpanHeader").toggleClass("Black");
其他提示
First you can simplify the function if you don't need to reuse the function, then it's an ID not a class so it should be #SpanHeader
$("a.SubCourses").click(function() {
$("#SpanHeader").toggleClass("Black");
});
You've just have a minor mistake in the css selector for the id
$("#SpanHeader").toggleClass("Black");
I've created a fiddle http://jsfiddle.net/26dUe/
You are selecting class .SpannerHeader element which is not exist in your DOM. Instead you should select by ID.
Like following:
$("a.SubCourses").click(onSubCourses);
function onSubCourses(e) {
e.preventDefault();
$("#SpanHeader").toggleClass("Black");
}
SpanHeader is a class. It is Id so, just change
$("a.SubCourses").click(onSubCourses);
function onSubCourses() {
$("#SpanHeader").toggleClass("Black");
}