1

無名関数を含む関数から値を返したい。

function getSingleCheckedItemId() {
    return $(".data-table-chk-item").each(function() {
      if ($(this).is(":checked")) {
          var value = $(this).attr("value");
          return value;
      }
    });
  }

この場合、すべてのチェックボックスの配列が返されます。最初の を削除するreturnと、値は返されませんが、undefined.

では、どのように から値を返すのgetSingleCheckedItemId()でしょうか?

4

3 に答える 3

5

.each always returns the jQuery object containing all elements that you iterated over so:

function getSingleCheckedItemId() {
    var ret;
    $(".data-table-chk-item").each(function() {
      if ($(this).is(":checked")) {
          ret = $(this).attr("value");
          return false; //breaks out of .each
      }
    });
    return ret;
}

Also, this.value is usually a better option than $(this).attr('value') in case you're dealing with form inputs - seems like you have radio/checkbox inputs due to their checked property. Also, this.checked returns a boolean so there's no need for $(this).is(':checked') either.


I believe your logic can be simplified to:

function getSingleCheckedItemId() {
    return $(".data-table-chk-item:checked").val();
}

This way .val() will return the value of the first :checked item or undefined if no elements are matched by the selector, which does the same as the loop above.

于 2013-03-13T11:54:29.850 に答える
2

あなたはそれを行うことができます:

function getSingelCheckedItemId() {
    var elements = $(".data-table-chk-item:checked");
    return (elements.length > 0) ? $(elements[0]).val() : undefined;
}
于 2013-03-13T12:01:38.260 に答える
1

私はこのようにします

function getSingleCheckedItemId() {
    var ret;
    $(".data-table-chk-item").each(function() {
        if ($(this).is(":checked")) {
            ret = $(this).attr("value");
        }
    });
    return ret;
}
于 2013-03-13T12:01:40.970 に答える