jQuery .wrap() isn't working

前端 未结 3 1540
心在旅途
心在旅途 2021-02-07 13:30

I\'m probably doing something wrong but I\'ve tried all sorts of things and can\'t seem to get a collection of jQuery objects wrapped. The following just outputs the link HTML,

相关标签:
3条回答
  • 2021-02-07 13:56

    jquery .wrap() returns the INNER element back to you, so it looks like nothing changed.

    $("<div>").wrap('<span>') 
    
    ===> 
    
    [<div></div>]
    

    which looks like it didn't work.

    but:

    $("<div>").wrap('<span>').parent()
    
    ===>
    
    [<span><div></div></span>]
    

    it actually did work.

    0 讨论(0)
  • 2021-02-07 13:58

    It looks like you mean to use jQuery's html method to add html in the second to last line - unless $dropdownSections is an array with each element being a jQuery object. I think you might be after this:

    $.each(sitemapSections, function(i) {
      var $sitemapSection = $(sitemapSections[i]);
      var $primary = $sitemapSection.find('[data-level="1"]').wrap('<h3></h3>');
    
      $dropdownSections.eq(i).html($primary.parent().html());
    });
    

    or more written another way:

    $.each(sitemapSections, function(i) {
      $dropdownSections.eq(i).html(
        $(sitemapSections[i])
        .find('[data-level="1"]')
        .wrap('<h3></h3>')
        .parent()
        .html()
      );
    });
    

    if $dropdownSections is an array which has a jQuery object in each element:

    $.each(sitemapSections, function(i) {
      $dropdownSections[i].html(
        $(sitemapSections[i])
        .find('[data-level="1"]')
        .wrap('<h3></h3>')
        .parent()
        .html()
      );
    });
    
    0 讨论(0)
  • 2021-02-07 14:07

    You need a string to pass into .html(), I think you're after this instead:

     $dropdownSections[i].empty().append($primary.parent());
    

    This gets the .parent() (since you just wrapped it in one) and sets the contents to that.

    0 讨论(0)
提交回复
热议问题