jQuery finding wrong elements under Chrome

2019-04-30 03:31发布

问题:

I'm using jQuery to iterate through an HTML table, and dynamically fill in the row numbers of each row (by populating the row number in a text box):

function updateRowNums() {
  $('#myTable').find('tr').each(function(index) {
    $(this).find('input[id$="_rowOrder"]').val(index);   
  });
}

This function gets called under:

$(document).ready(function() {
  // .. code truncated ... //
  updateRowNums();
});

This works perfectly fine under Firefox. However, under Chrome (tried both 5.x and 9.x (beta)) and sometimes Safari, this ends up populating a bunch of other fields that don't even match the:

'input[id$="_rowOrder"]'

criteria, with the row numbers. So basically it scatters the numbers around in other, unrelated, text fields...

I'm pretty sure this is some sort of Chrome or jQuery bug, but I'm just checking, since it seems like pretty basic functionality. BTW, if I introduce an alert in the code, it then works fine on Chrome, so this may have something to do with the timing of the document loading in Chrome:

function updateRowNums() {
  $('#myTable').find('tr').each(function(index) {
    alert("XXXXXXXXXXXXXXXXXXX");
    $(this).find('input[id$="_rowOrder"]').val(index);   
  });
}

Go here to see example:

http://jsfiddle.net/eGutT/6/

In this example, the steps you need to reproduce are:

  1. Go to URL using Chrome (or Safari -- sometimes fails as well).
  2. You will notice that everything works as expected so far (i.e. numbers filled down 1st column)
  3. Click on the "NAVIGATE AWAY" link.
  4. Click back
  5. You will see numbers filled in across top row AND down first column

You will notice that I added console logging, to output the ID's of the elements that are getting their value modified. The output of this log is:

one_rowOrder
two_rowOrder
three_rowOrder

which indicates that only 3 elements were touched. However, from the result, you can see that 5 elements have numbers in them.

Thanks, Galen

回答1:

The problem is that your input's do not have a name attribute. Chrome/Safari seems to try to save what you entered in to form fields when you go forward and back in the history. Because your inputs do not have name attributes its guessing which input field to put the values back in, and is guessing incorrectly.

Add name attributes to your fields and its all fixed: http://jsfiddle.net/petersendidit/eGutT/14/

Chrome/Safari probably should be checking for the id attribute of the name attribute is missing.



回答2:

If you are using digits as your IDs, jQuery won't recognize them and/or act correctly because it is invalid HTML. Either remove the digits or put a letter in front of them.