我想使用jQuery动画来跳转到页面上第一次出现的类,目前我正在使用一些基本代码,但是当我触发onclick事件时,我在控制台中出现错误。
这是我的RAZOR HTML:
@model List<Business.Models.InterviewCentres.InterviewCentresViewModel>
@{
ViewBag.Title = "Index";
}
<h2>
Interview Centre Bookings</h2>
<br />
The website is now showing dates between <b>@DateTime.Now.AddDays(21).ToShortDateString()</b>
and <b>@DateTime.Now.AddDays(92).ToShortDateString()</b>
@{
string previousLocation = "";
}
<!-- get each unique location and add to list. Will use this to build clickable links -->
@{
List<string> Locations = new List<string>();
}
@foreach (var item in Model)
{
if (!Locations.Contains(item.Location))
{
Locations.Add(item.Location);
}
}
<br />
@foreach (string location in Locations)
{
<a href="#" class="lnkNav"><span style="color: #772432; border-bottom-style: dotted;">@Html.Raw(location)</span>
 </a>
}
@foreach (var item in Model)
{
<table>
<tr>
<td>@Html.Label(item.CentreDateLocation)
</td>
<td>
<a href="@Url.Action("InterviewCentreInfo", "InterviewCentres", new { date = item.DateOfInterview.ToString(), centre = item.Location })">
<img src="@Url.Content("~/Images/excel.gif")" alt="Export grid data to excel" />
</a>
</td>
</tr>
</table>
<table>
<tr>
@foreach (var times in item.ListDateMemberNum)
{
if (previousLocation != item.Location)
{
previousLocation = item.Location;
<hr />
}
<td>
<div class = "@item.Location.Trim()">
@if (times.MemberNumber == "")
{ <div style="background-color: rgb(242, 246, 243); display: inline-block; padding-top: 2px;
padding-left: 2px; padding-right: 2px; padding-bottom: 2px;">
@Html.Raw(" ")
<img src="@Url.Content("~/Images/cross.gif")" alt="cross" />
@Html.Label(times.InterviewDate + " | ")
</div>
}
else
{
<div style="background-color: rgb(242, 246, 243); display: inline-block; padding-top: 2px;
padding-left: 2px; padding-right: 2px; padding-bottom: 2px;">
@Html.Raw(" ")
<img src="@Url.Content("~/Images/tick.gif")" alt="tick" />
<a href="@Url.Action("LookupPassword", "Membership", new { MemberNum = times.MemberNumber })" style="background-color:Red; color:White;">@times.InterviewDate</a>
</div>
}
</div>
</td>
}
</tr>
</table>
}
<script>
$('.lnkNav').click(function () {
var text = $(this).text();
$('html,body').animate({
scrollTop: $("." + text).offset().top
},
'slow');
});
</script>
当我点击类.lnkNav的锚点时,我得到了单击锚点的文本,这也是我要导航到的类的名称。然而,它不起作用。我添加了一些屏幕截图,以显示有文本的锚点,并且有相同名称的类。有谁知道我会如何实现这个?
答案 0 :(得分:0)
首先,您应该检查$('.' + text )
是否已定义。之后,你可以集中精力。
$('.lnkNav').click(function () {
var text = $(this).text();
if ($("." + text).length != 0) {
$('html,body').animate({
scrollTop: $("." + text).offset().top
},
'slow');
} else {
alert (" element not found!");
}
});