在我看来,我有:
@foreach (var comment in Model.commentList)
{
var id = comment.CommentId;
<div id="@(id)" style="height:100px; width: 100px; background-color: red; display:none;"></div>
<a id=@id onClick="ShowForm(this.id)" href="#">Comment</a>
}
然后我有一个脚本:
function ShowForm(clicked_id) {
var element = "#" + clicked_id;
$(element).fadeIn(1000);
}
我想要实现的是单击链接后显示某个元素,但它不起作用。我的错误在哪里?
最佳答案
第一点是ID应该是唯一的——ID意味着身份,如果它不唯一,你如何识别某个东西?
这可能是导致 jQuery 无法工作的原因。但是当您使用 jQuery 时,为什么不使用 jQuery 绑定(bind)您的点击呢?
我要做的就是为您的链接提供一个类,删除链接 ID 并将其放入 href(以便您的代码更易于访问),然后在文档准备好时使用 jquery 绑定(bind)您的点击:
$(function() {
$('.link').on('click', function(e) {
e.preventDefault(); // prevent default action of link
var link = $(this),
targetId = link.attr('href'), // get the href of the current link and use it as the id of the element
targetDiv = $(targetId);
targetDiv.fadeIn(1000); // fade in the div
link.hide(); // hide the link? not sure if you want to let them click it again
});
});
@foreach (var comment in Model.commentList)
{
var id = comment.CommentId;
<div id="@(id)" style="height:100px; width: 100px; background-color: red; display:none;"></div>
<a href="#@(id)" class="link">Comment</a>
}
示例:
$(function() {
$('.link').on('click', function(e) {
e.preventDefault(); // prevent default action of link
var link = $(this),
targetId = link.attr('href'), // get the href of the current link and use it as the id of the element
targetDiv = $(targetId);
targetDiv.fadeIn(1000); // fade in the div
link.hide(); // hide the link? not sure if you want to let them click it again
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" style="height:100px; width: 100px; background-color: red; display:none;"></div>
<a href="#test" class="link">Comment</a>
关于javascript - razor - 如何动态地将 id 插入 div 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43136450/