仅当div存在时才执行jquery代码

men*_*mam 16 css jquery

这是html代码:

<div id="popup" class="popup_block" >
 <img src="images/PUB-histRIRE.jpg" alt="popup" />
</div>
Run Code Online (Sandbox Code Playgroud)

和脚本:

<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>
Run Code Online (Sandbox Code Playgroud)

我喜欢只在页面上执行代码而没有thi div的div ...,只需忽略.我可以通过解析URL来制作一个if ...但它对我来说看起来更复杂......任何简单的jquery技巧?

mcg*_*ilm 37

if($('#popup').length >0 ){
   //your code here 
}
Run Code Online (Sandbox Code Playgroud)


Rus*_*rke 8

这样做的方法是(或者是)检查长度属性,如下所示:

if ($("#"+ popID).length > 0){
  // do stuff
}
Run Code Online (Sandbox Code Playgroud)


Tat*_*nen 7

像这样:

if($('div#popup').length) {
    // div exists
}
Run Code Online (Sandbox Code Playgroud)


Ila*_*sta 5

如果您需要一个简单的可重用解决方案,您可以扩展 jQuery:

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

然后:

$('#popup').ifexists(function(elem) {
    // do something...
});
Run Code Online (Sandbox Code Playgroud)