2

In my jQuery, am getting the student details which from the autocomplete selected item, like

var data = "<div class='close'><table><tr><td rowspan='4' width='50px;'>
     <img src='" + studentItem.Photo + "' Width='48' Height='48'  /></td><td>" + 
     studentItem.Name + " ( <span class='stuId'>" + studentItem.StudentId + 
     "</span> )</td><td align='right' ><div class='close16'/></td></tr><tr><td>
     <table cellpadding='0' cellspacing='0'><tr><td>" + studentItem.Email +
     "</td><td>&nbsp;|&nbsp;</td><td>" + studentItem.Mobile + "</td></tr></table>
     </td></tr></table></td></tr></table></div>";

and am binding this data to a div tag like

$("#students").append(data);

The problem here is I can get the same student again and again, and I can bind the same data again and again into this div tag.

So to restrict this I tried to set the condition before the data like,

if (!$('.stuId').is(studentItem.StudentId)) {
   var data=..........
}
else{
  alert('Duplicate data');
}

but its goin into the block even if the studentId already there in the div. How can I fix this, can anyone help me here

4

1 回答 1

3

Since we don't know what kind of StudentId you have, we can use filter (however, in some cases :contains might be enough):

var len = $('.stuId').filter(function() {
    return this.innerHTML == studentItem.StudentId;
}).length;

if (len == 0) {
    var data = ..........
} else {
    alert('Duplicate data');
}​

It will select all .stuId elements and filter the duplicates.

于 2012-05-26T08:51:04.917 回答