如何防止重复

时间:2010-11-30 18:34:44

标签: javascript jquery html

我正在试图找出如何让它循环遍历UL中的数据(每个li),并防止它重复任何先前存在的选择。

<script type="text/javascript" language="javascript">
// Long version
function HandlerCharacters() {
 var characterid = $('#charactersdrop option:selected').val();
 var characterName = $('#charactersdrop option:selected').text();

 if( characterid > 0 ) {
  // Create the anchor element
  var anchor = $( '<a href="#">Remove</a>' );  

  // Create a click handler for the anchor element
  anchor.click( function() {
   $( this ).parent().remove();
   return false;  // makes the href in the anchor tag ignored
  } );

  // Create the <li> element with its text, and then append the anchor inside it.
  var li = $( '<li>' + characterName + '&nbsp;</li>' ).append( anchor );
  li.data( 'characterid', characterid );

  // Append the new <li> element to the <ul> element
  $( '#characterlist' ).append( li );
 }
}
</script>

1 个答案:

答案 0 :(得分:1)

根据我的理解,您只是在新li不在列表中另一个characterID的数据范围内时尝试插入新的li。如果是这样,那么你可以写一个这样的函数:

function isDupe(which) {
  var result = false;
  $('ul#the_list li').each( function(i,e) { // look at all list elements
    if ( $(e).data('characterid') == which ) { // compare to argument
      result = true; // matched!
      return false; // break out of .each()
    }
  });
  return result;
}

然后你可以像这样包装你的li创建代码:

if( !isDupe(characterid) ){
  // do your checks
  // make your li
  // append to your list
}

以下是一个简化示例:http://jsfiddle.net/redler/B7myn/