Only add if it's not present
I only want to add this if it's not already present
$('#main_state').append('<label class="check error" generated="true">T开发者_开发问答his field is required.</label>');
So I have a loop and I only want to add it the first time...any ideas?
Something like this should do:
if ($('#main_state').html().indexOf('This field is required')==-1){
$('#main_state').append('<label class="check error" generated="true">This field is required.</label>');
}
Check the html in main_state for the occurrence of 'This field is required'
- if it can't be found -1
then add it as normal.
if($('label.check[generated=true]').length === 0) {
//do stuff...
}
Make a small jquery plugin like:
$.fn.appendif = function (selector, content) {
if ($(this).children(selector).length > 0) return this;
$(this).append(content);
return this;
}
And use one of the following:
$('#main_state').appendif('.check.error', '<label class="check error" generated="true">This field is required.</label>');
$('#main_state').appendif('label', '<label class="check error" generated="true">This field is required.</label>');
$('#main_state').appendif('label[generated="true"]', '<label class="check error" generated="true">This field is required.</label>');
I think this would be the easiest way.
UPD: I mean this is the easiest way if you do it in a jquery-style loop.
if( 0 == $('label[id=error_field]', $('#main_state') ).length )
{
$('#main_state').append('<label id="error_field" class="check error" generated="true">This field is required.</label>');
}
I wrote this out of the back of my head, but it should work, or atleast give you the idea.
with:
$('label[id=error_field]', $('#main_state') ).length
jquery checks if the element already exixts within $('#main_state')
element
From my comment: It seems that it does not depend on any loop variable so why don't you put the line before the loop?
If you cannot do that, the trivial solution would be to set a flag:
var added = false;
for(...) {
if(!added) {
// add the thing
added = true;
}
}
Granted, it is not that fancy and if you run the code that contains a loop a second time, the label will be added again. But from your description it seems you always want to add the label when you run the loop. This solution at least avoids querying the DOM.
精彩评论