CollapsiblePanelExtender: Can not get object in on

2019-08-19 05:09发布

问题:

I need to add a javascript event for CollapsiblePanelExtender on javascript pageload of the page. Following is the definition of CollapsiblePanelExtender:

    <cc1:CollapsiblePanelExtender ID="cpe" runat="Server" TargetControlID="pnlInstances" 
     BehaviorID="cpe" ImageControlID="lnkWebroleAction" ExpandedImage="~/App_Themes/Default/images/MonitorDownArrow16.png"CollapsedImage="~/App_Themes/Default/images/MonitorLeftArrow16.png" 
     CollapsedSize="0" Collapsed="false" ExpandControlID="lnkWebroleAction" CollapseControlID="lnkWebroleAction"
     AutoCollapse="false" AutoExpand="false" ExpandDirection="Vertical" SuppressPostBack="true" />

And following is the javascript code i am executing:

window.onload = pageLoad1();
    function pageLoad1() {$find("cpe").add_expandComplete(coll_ExpandedComplete);                                
    }

The problem is $find("cpe") returns null on this event. If i execute the same function from button click i can find the object.
Which other load events of javascript i can use? I have tried $(documnt).ready.

回答1:

You're not assigning the pageLoad1 function to window.onload, you're calling it immediately and assigning the value it returns (i.e. undefined).

You have to write:

window.onload = pageLoad1;  // No parenthesis.
function pageLoad1() {
    $find("cpe").add_expandComplete(coll_ExpandedComplete);
}

Or, alternatively, write a pageLoad() function, which will be called automatically by the framework when the page finishes loading:

function pageLoad() {
    $find("cpe").add_expandComplete(coll_ExpandedComplete);
}


回答2:

I agree with OP; there is (as original answerer pointed out) an error in the original post which is sufficient to make it look like there is not a real problem here; but I have a complex JS/Ajax driven page, and some code which tries to get some ASP.NET Ajax CollapsiblePanelExtender objects by their BehaviorID in a JS function which /is/ called on PageLoad.

These objects are usually ready, but sometimes aren't; if if try to run the code with a slight delay (100ms) they are ready. But delaying for a fixed time is not great; what event can I use, to know that these ASP.NET Ajax objects have finished building themselves?