开发者

Pass jquery events from aspx to ascx

开发者 https://www.devze.com 2023-01-21 03:54 出处:网络
I start开发者_开发问答ed using ascx yesterday and begun a process of chopping up my \"dynamic\" default.aspx page into smaller parts.

I start开发者_开发问答ed using ascx yesterday and begun a process of chopping up my "dynamic" default.aspx page into smaller parts.

In my default.aspx I have a lot of JavaScript/jquery code that handle different events. When I removed some html code from .aspx, while leaving the javascript in default.aspx, and placed it into .ascx the jquery events stopped working, do I have to write something special so that my JavaScript can access the html in my usercontrol?

Thanks M


take into consideration that element Ids change from stuff like Control1 to ctl00stuff_Control1 when you put them in user controls


The client side JavaScript has no knowledge of the ascx. The ascx's are included in the page before it is sent to the browser so the browser only sees it as a single page.

It is more likely the JavaScript stopped working because it could not find an element with a specific id or class. This could have happened for a number of reasons, such as the element is actually missing or the .net has dynamically changed the id.


I have pages that contain user controls that also contain other user controls. I had the same issue with events and the page rendering stack with this structure. To resolve this, I placed user control specific event management within a separate .js file such as mycontrol.js and referenced that .js within the .ascx file (put the link to it there).

I also had a situation where I did not have the user control rendered until placed within the markup (a sub-control) and thus the events could not be placed at that point. I handled this, by loading the user controls javascript within my javascript thus:

/* function to allow inclusion of other files 
Included this way to allow addition AFTER the page renders the control - that is, fake inclusion in this file
*/
function includeJS(jsPath)
{
    var script = document.createElement("script");
    script.setAttribute("type", "text/javascript");
    script.setAttribute("src", jsPath);
    document.getElementsByTagName("head")[0].appendChild(script);
};
includeJS('Js/secondusercontrol.js');
  • Separate script code for user controls and link within user controls
  • Include .js files using script if latency is an issue
  • put all "base" script and global objects (if needed) within the page .js file
  • use .live() and .delegate()

EDIT: one other option which may work for you I forgot initially is to use the .live() and/or the .delegate() functionality.

0

精彩评论

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

关注公众号