I'm trying to figure out how I can have it loop through the data in the UL (each li
) and prevent it from duplicating any prior existence of a selection.
<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开发者_Python百科; // 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 + ' </li>' ).append( anchor );
li.data( 'characterid', characterid );
// Append the new <li> element to the <ul> element
$( '#characterlist' ).append( li );
}
}
</script>
As I understand the question, you're trying to insert a new li
only when the new characterID
is not within the data of another li
in the list. If so, then you could write a function like this:
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;
}
Then you could wrap your li
creation code like this:
if( !isDupe(characterid) ){
// do your checks
// make your li
// append to your list
}
Here's a reduced example: http://jsfiddle.net/redler/B7myn/
精彩评论