开发者

Problem with breaking out Jquery each loop?

I have some html element like these:

 <table id="myTable"></table>

    <select name="mySelect">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    </select>

    <a href="javascript:void(0)" onclick="addToTable()">Add new</a>

    <script>
    addToTable = function() {
      var selected = $("select[name*='mySelect'] option:selected").val();
      $('#myTable').find('tr').each(function() {
        if ($(this).attr('id')==selected) { 
          alert('Record has already existed!'); return false;
        }
        else $('#myTable').append('<tr id="'+selected+'"><td>'+selected+'</td></tr>');
      });
    }
    </script>

The problem was: when I added two records (rows) with the same id, it a开发者_开发技巧lerted the message but kept appending the new row instead of breaking out the loop. What was I wrong here?

Thanks in advance.


What you are doing:

for every existing row R
  if R.id == newRow.id
    alert
    break
  else
    add newRow

This will add the newRow for each row that comes before an existing row with that id. With rows [1,2,3,4,5,6,7,8,9] and adding a row 9 will add that row 8 times before alerting "already exists".

What you mean to do is:

exists = false
for every existing row R
  if R.id == newRow.id
    existing = true
    alert
    break

if !exists
  add newRow

Equivalent in JS:

addToTable = function() {
  var selected = $("select[name*='mySelect'] option:selected").val();
  var exists = false;
  $('#myTable').find('tr').each(function() {
    if ($(this).attr('id')==selected) { 
      alert('Record has already existed!');
      exists = true;
      return false;
    }
  });
  if(!exists) {
    $('#favourite_hotels_table').append('<tr id="'+selected+'"><td>'+selected+'</td></tr>');
  }
}


I'm not sure, but maybe something wring with the else, and if you try like this ?

addToTable = function() {
    var selected = $("select[name*='mySelect'] option:selected").val();
    $('#myTable').find('tr').each(function() {
        if ($(this).attr('id') == selected) {
            alert('Record has already existed!');
            return false;
        } else {
          $('#favourite_hotels_table').append('<tr id="' + selected + '"><td>' + selected + '</td></tr>');
        }
    });
}


I created a fiddle for this http://jsfiddle.net/gj9eN/1/, but your code seems incorrect.

When there are no rows in the table to start with, the .each() on tr will never execute. Please provide more code to verify this?

Doesn't this work better (and shorter):

addToTable = function() {
    var selected = $("select[name*='mySelect'] option:selected").val();

    if ($("#" + selected) == undefined) {
        $('#myTable').append('<tr id="'+selected+'"><td>'+selected+'</td></tr>');
    } else {
        alert('Record already exists!');
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜