想要与 @Html 不同的值

本文关键字:@Html | 更新日期: 2023-09-27 18:32:10

每次用户单击图像时,我如何在javascript中获取确切的"PostId"的值

for (int i = 0; i < Model.Count; i++)
{
<img src="/images/icon_edit.gif" width="22" height="19" class="Edit" itemid="post" />
@Html.HiddenFor(x => x[i].PostId, new { @class = "postnew" })    
}

.JS:

$(document).ready(function () {
  $('.Edit').click(function () {
      alert($("#post").val());
      var params = { uname: $(this).val() };
      $.ajax({
          url: "/Profile/Post",
          type: "Get",
          data: { id: $("#post").val() }     
      });
  });
});

想要与 @Html 不同的值

您可以将帖子 ID 呈现为数据属性并使用 jQuery 访问该属性。

@for (int i = 0; i < Model.Count; i++)
{    
  <img src="/images/icon_edit.gif" width="22" height="19" class="Edit" data-post-id="@x[i].PostId" />   
}

j查询:

$(document).ready(function () {
  $('.Edit').click(function () {
      var $this = $(this), id = $this.data('postId');
      $.ajax({
          url: "/Profile/Post",
          type: "Get",
          data: { id: id }     
      });
  });
});

生成的img标记将如下所示:

 <img src... data-post-id="1" ... />

使用 jQuery,您可以使用 .data() 读取属性。用连字符分隔的名称将被驼峰化,因此postId .

但是,我们可以做得更好...

  1. 考虑使用 .on 处理所有当前和将来的点击事件,以处理用 .Edit 修饰的元素。如果以后可能会将具有.Edit的新元素添加到 DOM 中,这将非常有用,因为它们将自动包含在内。

     $(document).on('click', '.Edit', function() { /* ... */ });
    
  2. 请考虑使用语义有意义的标记,并将图像包装在锚点中,而不是使 img 可单击。然后,只需将锚点的href添加到帖子的 URL 中即可。然后,您可以取消数据属性,而只是您的 AJAX 调用。

    @for (int i = 0; i < Model.Count; i++)
    {    
       <a href="@Url.Action("Post", "Profile", new{id = x[i].PostId})" class="Edit"><img src="/images/icon_edit.gif" width="22" height="19" /></a>
    }
    $(document).ready(function () {
      $(document).on('click', '.Edit', function () {
          var url = $(this).attr('href');
          $.ajax({
              url: url,
              type: "Get"  
          });
      });
    });
    

带有 data 属性的解决方案很好,但如果你想使用隐藏字段,你可以使用 jQuery next() 选择器。

$(document).ready(function () {
  $('.Edit').click(function () {
      // the 'next' hidden field for the img
      var id = $(this).next().val(); 
      $.ajax({
          url: "/Profile/Post",
          type: "GET",
          data: { id: id }     
      });
  });
});