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

标签 jquery css

这是html代码:

<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 的页面上执行代码...在没有 thi div 的页面上,忽略即可。我可以通过解析 URL 来创建一个 if...但它对我来说看起来更复杂...任何简单的 jquery 技巧?

最佳答案

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

关于jquery - 仅当 div 存在时才执行 jquery 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5950435/

相关文章:

javascript - 为什么我的抵押贷款计算器显示的小数点位置不正确?

html - HTML 中的不同比例图像

html - 放置显示 : inline; in my #tabs id portion

javascript - 长时间运行的 AJAX 请求在几分钟后重新提交

javascript - 当您打开 Popover [bootstrap] 时,屏幕失去焦点并转到顶部

javascript - 如何在 Joomla 2.5 的页面中创建标签?

php - a href tel 和标准浏览器

javascript - 悬停个人资料图片后带箭头的工具提示框

jquery - chrome 中固定定位的 flexslider 和粘性导航的定位问题

html - css 调整以前的同级属性