2011-05-10 72 views
9

這裏是html代碼:執行jQuery代碼只有DIV存在

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

和腳本:

<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> 

我想與DIV只頁面上執行代碼...上沒有使用div的頁面,只是忽略。我可以做一個如果通過parsin的URL ...但它看起來更復雜的我......任何簡單的jQuery技巧?

回答

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

像這樣:

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

要做到這一點是這樣的(或者是)檢查length屬性,像這樣:

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

+1使用他的popID變量。如果你不打算在任何地方使用它,那麼沒有變量。 ;-) – Chris 2011-05-10 13:14:28

0

如果你需要一個簡單的可重複使用的解決方案,您可以擴展jQuery:

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

然後:

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