开发者

jQuery.wrap where contents not a direct descendant

开发者 https://www.devze.com 2023-02-13 02:44 出处:网络
I am trying to wrap selected nodes in a non-trivial structure, where the node will not (necessarily) be a direct descendant. It seems that wrap() is insufficient to use in a one-liner.

I am trying to wrap selected nodes in a non-trivial structure, where the node will not (necessarily) be a direct descendant. It seems that wrap() is insufficient to use in a one-liner.

I got it to work using replaceWith, using placeholder syntax to replace the original HTML. The following works fine and could easily be wrapped开发者_如何学编程 in a jQuery plugin. But I am curious if there is a better solution.

var template = '<div>\
                  <div>...</div>\
                  <div>{{original}}</div>\
                  <div>...</div>\
                </div>';

$('p').each(function() {
  var o = $(this).html();
  $(this).replaceWith(template.replace('{{original}}', o));
});


For more complex templates, you will want to look into the jQuery Template Plugin. It's still in beta, but it looks like it should provide a lot of flexibility. My original solution is still more compact, but using the jQuery.tmpl() function is close to a workable solution.

For the simpler cases, as described above, you're probably better off wrapping it in a 2-line plugin, like so:

$.fn.templateWrap = function(template) {
  return this.each(function() {
    var o = $(this).html();
    $(this).replaceWith(template.replace('{{original}}', o));
  });
}

Then call it using:

$('#target').templateWrap('<div>...{{original}}...</div>');

(Download jquery.templatewrap.min.js)

0

精彩评论

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