1

每次用户单击图像时,如何在我的 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() }     
      });
  });
});
4

2 回答 2

2

您可以将帖子 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" />   
}

jQuery:

$(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。然后,您可以取消 data 属性并简单地进行 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"  
          });
      });
    });
    
于 2013-09-21T07:46:55.217 回答
0

具有 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 }     
      });
  });
});
于 2013-09-26T08:45:22.490 回答