开发者

Inherit jquery code when loaded with ajax

I've got some jquery code to style some checkboxes on my page. I also have a table. This table doesn't show all rows when the page is loaded sans you have to load the rest of the rows with an ajax request. The problem is that the checkboxes in that ajax loaded rows won't be styled. I want to inherit the checkboxes styling to those checkboxes that have been load开发者_StackOverflow中文版ed with ajax.


Once the new checkboxes are loaded, you'll have to trigger your jQuery code to style those checkboxes (and only the new ones). Without seeing your code or markup it's impossible to give you a direct answer, but for instance, suppose your jQuery code adds a class to the checkboxes (presumably as part of, not all of, what it does; otherwise you'd just use CSS for styling). Then you'd simply have that code be sure to leave out those checkboxes:

var cbsToStyle = $(":checkbox:not(.foo)");

...and then style the cbsToStyle list.

Example (live copy):

HTML (obviously not the same as yours, but indicative):

<div id='container'>
  <label><input type='checkbox'>Original checkbox</label>
  <br><label><input type='checkbox'>Original checkbox</label>
  <br><label><input type='checkbox'>Original checkbox</label>
</div>

JavaScript using jQuery:

jQuery(function($) {
  var timer = 0,
      counter = 4;

  styleCheckboxes();
  timer = setInterval(loadCheckboxes, 1000);

  function loadCheckboxes() {
    var index;

    if (--counter < 0) {
      // Done
      cancelInterval(timer);
      timer = 0;
    }
    else {
      // Mimic adding three checkboxes
      for (index = 0; index < 3; ++index) {
        $("<br><label><input type='checkbox'>Another checkbox</label>").appendTo('#container');
      }

      // Re-trigger the styling code
      styleCheckboxes();
    }
  }

  function styleCheckboxes() {
    // Get only those we haven't styled before and style them.
    // Note that the class is used as a marker (you might _also_
    // use it to apply some style rules)
    $(":checkbox:not(.styled)").addClass("styled").css("width", "40px");
  }

});​

...where styleCheckboxes is the most relevant bit.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜