剃刀 - 如何动态地将id插入div元素

时间:2017-03-31 08:53:42

标签: javascript razor

在我看来,我有:

@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);
}

我想要实现的是在点击链接后显示某个元素但它不起作用。我的错误在哪里?

3 个答案:

答案 0 :(得分:1)

问题是你要设置两个具有相同ID的元素

尝试更改您的cshtml

debugger;

答案 1 :(得分:1)

第一点是ID应该是唯一的 - ID意味着身份,如果它不是唯一的,你如何识别某些东西?

这可能是导致你的jQuery无法工作的原因。但是当你使用jQuery时,为什么不用jQuery绑定你的点击?

我要做的是给你的链接一个类,删除链接ID并将其放入href(这样你的代码将更易于访问),然后使用jquery在你准备的文件上绑定你的点击:

$(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>

答案 2 :(得分:-1)

@之前的foreach将导致Razor将循环内容解释为C#。

尝试使用&#34; @:&#34;为循环内的HTML行添加前缀,如下所示:

@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>
}
相关问题