简体   繁体   中英

How can I make a function return true after functions within jQuery's .each() finishes?

I'm using knockout.js. I have several editable grids in a form, and the names of the fields inside those grids matter, so using uniqueName isn't an option.

So what I'm doing is calling a function to rename the fields when the user clicks submit.

function renameFields(o, index) {
  var el_name    = $(o).attr('name');
  var name_index = el_name.lastIndexOf('_') + 1;

  $(o).attr('name', el_name.substring(0, name_index) + index);
}

function Submit() {
  self.submit = function() {
    // Use unique AND meaningful input/textarea [name]s in .grids.
    window.index_arr = [];

    $('.grid').each(function() {
      $(this)
      .children('.row')
      .each(function(i){
        window.index_arr.push(i);

        $(this)
        .find('input, textarea')
        .each(function() {
          renameFields($(this), window.index_arr[i]);
        })
      })
    });

    // Submit the form
    return true;
  }
}

renameFields works fine, but true is returned before it's called on every field.

Let Knockout do the dirty work of keeping the indices of your attributes up to date with something like this:

HTML:

<div id="grid" class="grid">
    <div class="row" data-bind="foreach:rows">
        <input data-bind="attr: { name: 'string_' + $index() }">
        <textarea data-bind="attr: { name: 'string_' + $index() }">
    </div>
</div>

View model:

var vm = {
    rows: ko.observableArray()
};

ko.applyBindings(vm, document.getElementById("grid"));

Please give us more about how you are setting up the click handlers...

I'll take a SWAG at it... I think you are dealing with hoisting

Without a fiddle I can't test it, but try the following code.

var renameFields = function(o, index) {
  var el_name    = $(o).attr('name');
  var name_index = el_name.lastIndexOf('_') + 1;

  $(o).attr('name', el_name.substring(0, name_index) + index);
}

var Submit = function() {
  self.submit = function() {
    // Use unique AND meaningful input/textarea [name]s in .grids.
    window.index_arr = [];

    $('.grid').each(function() {
      $(this)
      .children('.row')
      .each(function(i){
        window.index_arr.push(i);

        $(this)
        .find('input, textarea')
        .each(function() {
          renameFields($(this), window.index_arr[i]);
        })
      })
    });

    // Submit the form
    return true;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM