【问题标题】:jquery how to iterate through a list of attribute valuesjquery如何遍历属性值列表
【发布时间】:2012-04-11 16:59:30
【问题描述】:

我有这个方法:

$("#btnupdateofficeapprovers").click(function () {
        var checkedInvoiceLineIds = $(":checked").attr("data-invoicelineid");

        checkedInvoiceLineIds.each(function (index) {
            alert(index + ': ' + $(this).text());
        });
    });




<table>
        @foreach (var item in Model.Invoice.InvoiceLines) {
            <tr class="subheader">
                <td>
                    <input type="checkbox" class="invoicelinecombobox" data-invoicelineid=@item.InvoiceLineId >
                </td>
            </tr>

        }
    </table>

<div id="updateapproversdiv">
    @Html.DropDownListFor(modelItem => Model.Invoice.ApprovedForPaymentUserId, Model.OfficeApprovers, new { @class = "officeapproverddl" })
    <input type="button" id="btnupdateofficeapprovers" class="button invisibleforprint" value="Update" />
</div>

我想要做的是获取所有 invoicelineid 并将它们放入一个集合中。

接下来我要遍历列表中的每个 id 并将其显示在警报中。

问题是这引发了一个很大的异常。有谁知道如何解决?这个怎么做?

【问题讨论】:

    标签: jquery jquery-selectors custom-data-attribute


    【解决方案1】:

    您可以简单地使用 jQuery 选择器“具有属性”:http://api.jquery.com/has-attribute-selector/

    jsFiddle:http://jsfiddle.net/NF5Ss/1/

    $("#btnupdateofficeapprovers").click(function () {
        var checkedInvoiceLineIds = $(":checked[data-invoicelineid]");
    
        console.log(checkedInvoiceLineIds);
    
        checkedInvoiceLineIds.each(function(index) {
           alert(index + ': ' + $(this).data('invoicelineid'));
        });
    });​
    

    【讨论】:

      【解决方案2】:

      attr() 返回一个字符串。您不能使用each() 迭代字符串。这可能是你想要做的:

      $("#btnupdateofficeapprovers").click(function () {
          var ids = $("input:checked").attr("data-invoicelineid").split(' ');
          $.each(ids, function(i, v) {
              alert(i + ': ' + v);
          });
      });
      

      编辑:你也可以像 @Armatus 建议的那样做:

      $("#btnupdateofficeapprovers").click(function () {
          var $els = $("input:checked");
          $els.each(function(i){
              alert(i + ': ' + $(this).attr('data-invoicelineid'));
          });
      });
      

      【讨论】:

        【解决方案3】:

        .each 遍历一个 jquery 对象。您将 checkedInvoiceLineIds 分配给 .attr() ,它是一个字符串并且没有 .each

        使其 =$(':checked') 然后在 .each 中访问它的 .attr。

        【讨论】:

          猜你喜欢
          • 2019-01-25
          • 2016-05-26
          • 1970-01-01
          • 2017-10-14
          • 2012-03-03
          • 2012-01-26
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多