简体   繁体   中英

ASP.NET How do I get this jQuery to work persistently across page loads / post backs?

In ASP.NET I'm trying to use mColorPicker (http://blog.meta100.com/post/600571131/mcolorpicker) with a page I have.

It works on initial page load, can pick the colors fine and I have it hooked up how I want. However, when I update the page (click a button to display another panel / hide other ones), it suddenly stops working as if the javascript isn't there.

I have this code:

<script type="text/javascript">
  $(document).ready(function () {
    $('#color3').bind('colorpicked', function () {
      $(".P_FrameDisplay_222").css("background-color", $(this).val());
    });
  });
</script>
...
<div style="margin: 5px; float: left;">
  <input type="color" id="color3" value="#ff0667" data-text="hidden" style="width: 40px; height: 40px; border-style: none;" />
</div>

I've had this problem before with different javascript code, and to fix it I use this pageload javascript function.

<script type="text/javascript">
  function pageLoad() {
    imagePreview();
  }
</script>

How can I get this to work persistently across page loads / post backs?

I am assuming that you use updatepanels, in that case you can use the page request manager which manages partial page updates. Like this:

//some initialization code

var prm = Sys.WebForms.PageRequestManager.getInstance();

prm.add_endRequest(function (sender, args) {
    //some initialization code
});

It appears you are using update panels (I am assuming because of the pageLoad function). So remember whatever you run on $(document).ready , you will also need to run in the pageLoad funciton (if the content is replace).

Assuming you're using the latest* jQuery, try this snippet, but put it outside the update panel: (assuming #color3 will only show up once, if you need it to work on a class of elements you should define a ... class)

<script type="text/javascript">
  $(document).ready(function () {
    $('#color3').live('colorpicked', function () {
      $(".P_FrameDisplay_222").css("background-color", $(this).val());
    });
  });
</script>
  • As of jQuery 1.4 the .live() method supports custom events as well as all JavaScript events that bubble. [emphasis mine]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM