2011-05-10 8 views
9

aquí es el código HTML:Ejecutar el código jQuery sólo si existe div

<div id="popup" class="popup_block" > 
<img src="images/PUB-histRIRE.jpg" alt="popup" /> 
</div> 

y guión:

<script type="text/javascript"> 
    $(document).ready(function(){ 

      popWidth = 690; 
      popHeight = 550; 
      popID = 'popup'; 

      var popMargTop = popHeight/2; 
      var popMargLeft = popWidth/2; 

      //Apply Margin to Popup 
      $('#' + popID).css({ 
       'width': popWidth, 
       'height': popHeight, 
       'margin-top' : -popMargTop, 
       'margin-left' : -popMargLeft, 
       'visibility' : 'visible' 
      }); 

      //Fade in Background 
      $('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag. 
      $('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer 

     //Close Popups and Fade Layer 
     $('a.close, #fade, .popup_block').live('click', function() { //When clicking on the close or fade layer... 
      $('#fade , .popup_block').fadeOut(); //fade them both out 
      $('#fade').remove(); 
      return false; 
     }); 

    }); 
    </script> 

me gusta para ejecutar el código sólo en la página con el div ... de página sin thi div, solo ignora. Puedo hacer un si revisando la URL ... pero me parece más complicado ... ¿algún truco simple de jquery?

Respuesta

23
if($('#popup').length >0){ 
    //your code here 
} 
5

De esta manera:

if($('div#popup').length) { 
    // div exists 
} 
2
if ($("#popup").length) { 
    // do popup stuff 
} 
7

La manera de hacer esto es (o era) para comprobar la propiedad de longitud de este modo:

if ($("#"+ popID).length > 0){ 
    // do stuff 
} 
+0

+1 por usar su variable de popID. No tiene sentido tener la variable si no vas a usarla en todas partes. ;-) – Chris

0

Si necesita un simple solución reutilizable, puede extender jQuery:

$.fn.extend({ 
    'ifexists': function (callback) { 
     if (this.length > 0) { 
      return callback($(this)); 
     } 
    } 
}); 

continuación:

$('#popup').ifexists(function(elem) { 
    // do something... 
}); 
Cuestiones relacionadas