Execute the jquery code only if div exist
here is the html code :
<div id="popup" class="popup_block" >
<img src="images/PUB-histRIRE.jpg" alt="popup" />
</div>
and script :
<script type="text/javascript">
$(document).ready(function(){
popWidth = 690;
popHeight = 550;
popID = 'popup';
var popMargTop = popHeight / 2;
var popMargLeft = popWidth / 2;
开发者_如何学JAVA //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>
I like to execute the code only on page with the div... on page without thi div, just ignore. I can make a if by parsin the URL... but it look more complicated to me... any simple jquery trick ?
if($('#popup').length >0 ){
//your code here
}
Like this:
if($('div#popup').length) {
// div exists
}
The way to do this is (or was) to check the length property like so:
if ($("#"+ popID).length > 0){
// do stuff
}
If you need a simple reusable solution, you could extend jQuery:
$.fn.extend({
'ifexists': function (callback) {
if (this.length > 0) {
return callback($(this));
}
}
});
Then:
$('#popup').ifexists(function(elem) {
// do something...
});
if ($("#popup").length) {
// do popup stuff
}
Let's use each and possibly first .
If you want to execute the code on each match:
$("#popup").each(function(index, element){
//Do stuff. Use $(element) and/or index as necessary
});
If you want to execute the code only once if a match is found:
$("#popup").first().each(function(index, element){
//Do stuff. Use $(element) as necessary.
});
精彩评论