我正在尝试在点击后为元素添加css
类。
但我不能这样做。
我的这个动作的目标是,在我点击一个元素的第一级菜单中,它会以另一种颜色显示。
例如,请访问此链接。
http://www.templatemonster.com/demo/50935.html
可能因为点击后刷新页面而出现此问题!我不确定。
我该怎么做?
(我使用过ASP.NET和Umbraco CMS)
<script type="text/javascript">
jQuery(function (evt) {
$("[class*='firstLevelOfMenu'] ").click(function (event) {
event.stopPropagation(); // stops click event from bubbling up from child
$(this).addClass('current-menu-item page_item page-item-203 current_page_item');
});
})
</script>
MyHelpers.cshtml:
@helper Navigation(int parentId, int depthNavigation = 3)
{
IPublishedContent parent = Node.ContentCache.GetById(parentId);
if (parent.Level <= (depthNavigation - 1) && parent.GetPropertyValue("UmbracoNaviHide").Equals(false) && parent.Children().Count() > 0)
{
if (parent.Level > 1)
{
<ul style="visibility: hidden; display: none;" class="sub-menu">
@foreach (IPublishedContent child in parent.Children())
{
if (child.Level <= depthNavigation && child.GetPropertyValue("UmbracoNaviHide").Equals(false))
{
<li class="menu-item menu-item-type-post_type menu-item- object-page">
<a href="@child.Url">@child.Name</a>
@Navigation(child.Id, depthNavigation)
</li>
}
}
</ul>
}
else
{
foreach (IPublishedContent child in parent.Children())
{
if (child.Level <= depthNavigation && child.GetPropertyValue("UmbracoNaviHide").Equals(false))
{
<li id="menu-item-@child.Id" class="firstLevelOfMenu
menu-item
menu-item-type-post_type
menu-item-object-page">
<a href="@child.Url">@child.Name</a>
@Navigation(child.Id, depthNavigation)
</li>
}
}
}
}
else
{
foreach (IPublishedContent child in parent.Children())
{
if (child.Level <= depthNavigation && child.GetPropertyValue("UmbracoNaviHide").Equals(false))
{
<li>
<a href="@child.Url">@child.Name</a>
@Navigation(child.Id, depthNavigation)
</li>
}
}
}
}
答案 0 :(得分:0)
DOM更改不是持久性的。恰好发生了你所说的话:this problem occurred because of refreshing the page after clicking
。
要发生此行为,您必须在页面加载时进行更改,而不是在单击链接时进行更改,因为加载新页面时这些更改将会丢失。
您必须阅读网址,&#34;发现&#34;什么链接必须改变并采取适当的行动。
例如,假设您在http://exampledomain.com
上有3个链接,以这种方式指向每个链接:
http://exampledomain.com/about-us
http://exampledomain.com/buy-something
http://exampledomain.com/find-my/dog
然后,你应该有这个脚本:
$( document ).ready(function() {
/* This will get the path part of the
* URL (The string after the domain) and
* split it into an array .*/
var path = window.location.pathname.split("/");
/* The we will remove the starting / if there's any */
if (path.length > 1) {
path.splice(0, 1);
}
/* We check if there's actually a path */
if (path.length > 0) {
return;
}
/* And then, we check for the different links */
switch(path[0]) {
case "about-us":
$("#link1").addClass('yeah');
break;
case "buy-something":
$("#link2").addClass('yeah');
break;
case "find-my":
$("#link3").addClass('yeah');
break;
}
});