Use jQuery to move WordPress post attachments to per-post dynamically-created lists?

痞子三分冷 提交于 2019-12-02 10:54:53
Leo

Check this:

jQuery("document").ready (function($){
  var matchesEl = ".para a:has(img), .para iframe"
  $('.wrapper940').each(function(index){

    if ($(this).find(matchesEl).length > 0) {

      $('<ul>').insertBefore($(this).children('.title'));

      $(this).find(matchesEl).each(function() {
        //The line code under will only works if all your .wrappers940 always have at least one matched element.
        //$("<li>").append($(this)).appendTo($('.wrapper940 ul').eq(index));
        //So the right code is:
        $("<li>").append($(this)).appendTo($('.wrapper940').eq(index).children('ul'));
      });

    }
    $('p').filter(function () { return $.trim(this.innerHTML) == "" }).remove();
  });
});

Commenting code:

1) If you want only to move the image, you use .para img, but I think you want to move the element <a> with the <img>, so you can use: .para a:has(img).

2) The index var here $('.wrapper940').each(function(index){ is important to match the right ul in this line: $("<li>").append($(this)).appendTo($('.wrapper940 ul').eq(index));

3) This line will remove blank <p> tags: $('p').filter(function () { return $.trim(this.innerHTML) == "" }).remove(); after you move their content into <li>s

Codepen: http://codepen.io/anon/pen/wDmsi

Answering your questions in comments:

1) The index is the index number of your element matched in each(). The base number is 0. So if you have 10 .wrapper940 in your page, the first one will have index = 0, the second will have index = 1, til the last and 10th will have index = 9. We use it here to force code not send the img and iframes to the wrong .wrapper940. It says img and iframes from .wrapper940 index 6 belongs to .wrapper940 index 6. Writing this I just discovered a fail in my code. Check the code above to see the changes.

2) I always used this for pure javascript and $(this) for jquery. It seems like $(this) have more properties, like we see here: Difference between $(this) and this in jquery but using the $(...) consume more processing. So you can always test if both works on each case and use just this.

3) You can simplify:

var newUl = $("<ul></ul>");
newUl.insertBefore($(this).children('.title'));

To

$('<ul></ul>').insertBefore($(this).children('.title'));

And from this to

$('<ul>').insertBefore($(this).children('.title'));

4) The funcion appendTo(), insertBefore() and similars are already a kind of echo. I believe that if the element exist, the jQuery will move it. If it won't exist, jQuery will create it, but I can't confirm conclusively.

5) This trick of clear <p> tags is kind magic to me too. I don't know exactly how it works. I got the code from here: Remove "empty" paragraphs with jQuery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!