【问题标题】:Click dynamically created buttons单击动态创建的按钮
【发布时间】:2014-09-27 02:57:49
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: jquery asp.net-mvc button view


    【解决方案1】:

    当您为每个项目生成 html 时,将数据属性添加到包含您未显示的值的按钮,以便可以在单击事件中检索它们。请注意为按钮使用类名(不是 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();
      ....
    }
    

    【讨论】:

    • 很好,工作。但不得不将@Model[i] 更改为@Model.ElementAt(i),因为不能在IEnumerable 上使用索引。并感谢您提供额外的脚本信息。不得不查找“最近的”,但现在明白了。工作很漂亮...... ;-)
    • 那么您不需要 for 循环(正如您在问题中指出的那样)。如果是IEnumerable,您可以使用foreach 循环,例如foreach(var item in Model) { ... 并使用 @item.Name
    • 原来我用的是foreach。但是,我需要计数,因为我想在突出显示的部分中最多显示前 5 个项目,然后在另一个循环中显示其余部分。有没有办法使用foreach进行计数?这就是我切换到 For 循环的原因。再次感谢,一点一点学习...
    • 只有当你在循环外声明一个计数器时,它才会在 int index = 0; foreach(var item in Model) {....; index++;} 内递增。但无论哪种方式都可以。
    【解决方案2】:

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

    @foreach (var answer in Model)
    {
        .....
    
    
        <button type="button" data-id="@answer.ID" class="seeComments">See comments</button>
    }
    

    如果您的模型类包含名为 Answers 的嵌套 IEnumerable 属性,则如下所示

    @foreach (var answer in Model.Answers)
    {
        .....
    
    
        <button type="button" data-id="@answer.ID" class="seeComments">See comments</button>
    }
    

    然后使用.seeComments 选择器为所有See Comments 按钮绑定点击事件,并使用.data("id") 来获取id,如下所示

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

    【讨论】:

      猜你喜欢
      • 2016-06-30
      • 2020-04-12
      • 1970-01-01
      • 2011-09-05
      • 1970-01-01
      • 2014-02-23
      • 1970-01-01
      • 2018-06-17
      相关资源
      最近更新 更多