单击动态创建的按钮

时间:2014-09-27 02:57:49

标签: jquery asp.net-mvc button view

我正在使用MVC,在我的视图中,我使用For循环动态生成内容。在每个循环中,我插入一个“查看注释”按钮。

如果我点击第一个“查看评论”按钮,如何让它执行与第一个块中的数据相关的代码(例如洗碗碟信息)?例如,由于按钮是动态生成的,我如何从模型中获取该行数据的ID?

我想在jQuery代码下面使用。但我不知道如何获取该特定行的ID。

 $("#seeComments").click(function () {
        alert(ID);
    });

Dynamic button generation

2 个答案:

答案 0 :(得分:2)

当您为每个项目生成html时,将数据属性添加到包含您未显示的值的按钮,以便可以在click事件中检索它们。注意使用按钮的类名(而不是ID属性),因为您将有重复的ID,这是无效的html。

例如

@for(int i = 0; i < Model.Count; i++)
{
  <div class="answer"> // wrapper to allow selection
    <div class="heading">
      <span class="name">@Model[i].Name</span>
      <span class="rating">@Model[i].Rating</span>
    </div>
    .....
    <button class="comments" type=button" data-id="@Model[i].ID">See Comments</button>
    .....      
  </div> 
}

和脚本

$('.comments').click(function() {
  var id = $(this).data('id');
  var rating = $(this).closest('.answer').find('.rating').text();
  ....
}

答案 1 :(得分:1)

您可以将相关行的ID放在按钮的data-id属性中,并将seeComments设置为按钮的class。您没有包含模型类定义,因此假设它是IEnumerable,您的视图代码将是这样的

@foreach (var answer in Model)
{
    .....


    <button type="button" data-id="@answer.ID" class="seeComments">See comments</button>
}
如果您的模型类包含名为IEnumerable

的嵌套Answers属性,请使用下面的

@foreach (var answer in Model.Answers)
{
    .....


    <button type="button" data-id="@answer.ID" class="seeComments">See comments</button>
}

然后使用See Comments选择器绑定所有.seeComments按钮的点击事件,并使用.data("id")抓住ID,如下所示

$(".seeComments").click(function () {
    // this will display the data-id value of the clicked button
    alert($(this).data("id"));
});