开发者

Hide div doesn't work?

I have div which it is hidden by default , when the use clicks show link the following javascript method is called:

function ChangeControlVisibility(elementID) {
    var  element = $("#" + elementID);
    if (element.css('display') != 'block' && element.css('display') != 'table') {
        element.show();
        var tempElement = $('div.expanded');
        if (tempElement.length > 0) {
            tempElement.css('background-image', 'url(../images/arrow1.gif)');
        }
    }
    else {
        element.hide();
        var tempElement = $('div.expanded');
        if (tempElement.length > 0) {
            tempEle开发者_运维百科ment.css('background-image', 'url(../images/arrow2.gif)');
        }  
    } 
}

this step works but when i call the previous method at page_load event the method doesn't work: element.css('display') undefined.

Is there any problem at the previous code????


Do you execute that code within the .ready() handler?

And by the way, unless you really need to explicitly check for display-state table, you could just ask for

$(document.ready(function(){
   if (!element.is(':visible')){
   }
   else{
   }
});

Ref.: .is(), .ready(), :visible


You can simplify it overall by using .toggle() and the :visible selector, like this:

function ChangeControlVisibility(elementID) {
  var vis = $("#" + elementID).toggle().is(':visible');
  $('div.expanded').css('background-image', 'url(../images/arrow' + (vis ? '1' : '2') + '.gif)');
}

This toggles the visibility (via .hide()/.show() under the covers) and checks the resulting visibility to see if it's shown in the page or not, and sets the arrow image according to this.


Have a look at the :hidden and :visible jQuery selector. and try something like this:

function ChangeControlVisibility(elementID) { var hiddenElement = $("#" + elementID + ":hidden"); var element = $("#" + elementID); if (hiddenElement.length > 0) { //to check if this element exists hiddenElement.show(); var tempElement = $('div.expanded'); if (tempElement.length > 0) { tempElement.css('background-image', 'url(../images/arrow1.gif)'); } } else { element.hide(); var tempElement = $('div.expanded'); if (tempElement.length > 0) { tempElement.css('background-image', 'url(../images/arrow2.gif)'); }
} }

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜