<!--language: lang-html-->
@foreach (var book in Model.Category.Books)
{
<div class="rate-star-@book.Id"></div>
<script>
$(".rate-star-@book.Id").stars({ stars:5, readonly:false});
</script>
}
关于我正在尝试做的事情的简短说明: 循环内的脚本代码是我需要为页面上的书籍实现的星级评分插件之一。这里的问题是,我需要在主体中进一步包含 jquery 代码,但由于 JQuery 库加载晚于脚本代码,所以我收到“$ 未定义”错误。
我尝试过什么:
我尝试在此页面上实现该解决方案
[Handling code which relies on jQuery before jQuery is loaded由 Ashkan Mobayen Khiabani 编写。我将代码放在一个函数中。该函数在主体的底部被调用。它应该被调用与每次迭代中创建的次数一样多。但由于它仅在底部调用一次,因此其他创建的函数不会运行,因此只有一本书受到该函数的影响。
<!--language: lang-html-->
@foreach (var book in Model.Category.Books)
{
<div class="rate-star-@book.Id"></div>
<script>
function rateStar{
$(".rate-star-@book.Id").stars({ stars:5, readonly:false});
</script>
}
}
@section scripts
{
<script>
rateStar();
</script>
}
那么如何使该函数被调用与文档中创建的次数一样多呢?
最佳答案
在Views/Shared
中打开_Layout.cshtml
并在head标签中创建一个脚本标签并创建一个数组(让其将其命名为postJquery
:
<head>
...
<script>var postJquery = [];</script>
...
</head>
现在,在同一个文件 (_Layout.cshtml
) 中,转到底部并在 body 标记结束之前添加以下代码:
<script>for(var i=0;i<postJquery.length;i++) postJquery[i]();</script> //just ad this line
</body>
现在,您需要运行依赖于 jquery 的代码的任何地方,只需将其添加到函数中并将其添加到 postJquery
数组中,它将在 jQuery 加载后运行,如下所示:
postJquery.push(function(){
//your code goes here
});
例如,您的情况是:
@foreach (var book in Model.Category.Books)
{
<div class="rate-star-@book.Id"></div>
<script>
postJquery.push(function(){
$(".rate-star-@book.Id").stars({ stars:5, readonly:false});
});
</script>
}
}
上面的代码运行得很好,但是我不喜欢它,因为每个图书项目都会重复脚本标签及其内容,例如,如果您的循环中有 20 本书,则以下代码将重复 20 次(当然,每一次的图书 ID 都会改变):
<script>
postJquery.push(function(){
$(".rate-star-@book.Id").stars({ stars:5, readonly:false});
});
</script>
所以我会做这样的事情:
@foreach (var book in Model.Category.Books)
{
<div class="rate-star" data-id="@book.Id"></div>
}
<script>
postJquery.push(function(){
$(".rate-star").stars({ stars:5, readonly:false});
});
</script>
因为我不知道 .stars
是否应该在单个元素上使用(并且单击上面的代码会影响所有项目),您可以这样做:
@foreach (var book in Model.Category.Books)
{
<div class="rate-star" data-id="@book.Id"></div>
}
<script>
postJquery.push(function(){
$(".rate-star").each(function(){
$(this).stars({ stars:5, readonly:false});
});
});
</script>
关于javascript - 脚本代码不在 foreach 循环内运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55559519/