javascript - razor - 如何动态地将 id 插入 div 元素

标签 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);
}

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

最佳答案

第一点是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/

相关文章:

javascript - javascript中实例的__proto__与其构造函数的原型(prototype)之间的关系

javascript - 查找对象键之间的差异

c# - 如何从 Controller MVC3 动态添加代码(或标记)到 View 代码

c# - 为自己的助手创建使用?像 Html.BeginForm

c# - 部分/部分中的 asp.net mvs 部分?

javascript - 如何将 JavaScript 与 Razor 代码混合使用

javascript - AngularJS:在 ng-repeat 中为 div 设置相同的高度

javascript - 使用 JavaScript 将元素添加到 html 多级列表

javascript - 使用 JavaScript 检查 NodeJS 的真实 IP 地址

asp.net-mvc-3 - 模型绑定(bind)器和隐藏字段