javascript 想知道如何在jquery或JS中实现类似于 *ngFor/ng-repeat的内容

zmeyuzjn  于 2023-01-01  发布在  Java
关注(0)|答案(4)|浏览(111)

在jQuery或普通JS中是否可能有类似的ngForng-repeat概念?
想做一些类似的事情,但不是在角的方式。

<div *ngFor="let inputSearch of searchBoxCount" class="col-sm-12">
    <textarea name="{{inputSearch.name}}" id="{{inputSearch.name}}" rows="2" class="search-area-txt" attr.placeholder="{{placeholder}} {{inputSearch.name}}">
    </textarea>
</div>

可以与data=""属性一起使用,只要有意义即可。

zpqajqem

zpqajqem1#

如果你想在javascript中使用它,你必须在一个循环中动态地创建元素。* angular中的ngFor和ngRepeat是包含模板绑定的指令,我们在javascript或jquery中都没有。一旦指令遇到angular,尝试呈现各自的模板,直到循环结束。通过javascript我们可以这样做。如果你想把6个divs添加到body元素中,并分别添加id,你必须按照下面的方法操作。

var array = ['first', 'second', 'third', .......so on];
for(var i=0; i<array.length; i++){
   var elem = document.createElement("div");
   elem.setAttribute('id', array[i]);
   document.body.appendChild(elem);
}

我们不能像在Angular中那样使用ngFor。

nkhmeac6

nkhmeac62#

const anArray = [
        { tittle: "One", body: "Example 1" },
        { tittle: "Two", body: "Example 2" }
    ]
    
    function ngForFunctionality() {
        let value = '';
        anArray.forEach((post) => {
            value += `<li>${post.tittle} - ${post.body}</li>`;
        });
        document.body.innerHTML = value;
    };
    
    ngForFunctionality();
<body></body>
gzszwxb4

gzszwxb43#

在JQuery中,我会这样做:
超文本:

<div class="searchbox-container col-sm-12">        
</div>

JavaScript语言:

var textAreas = $.map(searchBoxCount, function(inputSearch) {
    return $("<textarea></textarea")
      .attr({
        name: inputSearch.name,
        id: inputSearch.name
        rows: "2",
        placeholder: placeholder + " " + inputSearch.name
      })
      .addClass("search-area-txt");
});

$('.searchbox-container').append(textAreas);
mfuanj7w

mfuanj7w4#

没有简单的方法可以通过vanilla得到类似的ngFor,但是这是可能的!
我的实现(您可以使用更多的正则表达式使它更好):
HTML代码:

<ul id="my-list">
      <li *for="let contact of contactsList">
        <span class="material-icons">{{ contact.icon }}</span>
        <span>{{ contact.value }}</span>
      </li>
    </ul>

用于实现*for(如Angular的*ngFor)的JS代码:

/**
 * (*for) cicle implementation
 * @param element the root element from HTML part where you want to apply (*for) cicle. This root element cannot to use (*for). Just children are allowed to use it.
 * @returns void
 */
function htmlFor(element) {
  return replace(element, element);
}

/**
 * Recursive function for map all descendants and replace (*for) cicles with repetitions where items from array will be applied on HTML.
 * @param rootElement The root element
 * @param el The mapped root and its children
 */
function replace(rootElement, el) {
  el.childNodes.forEach((childNode) => {
    if (childNode instanceof HTMLElement) {
      const child = childNode;
      if (child.hasAttribute('*for')) {
        const operation = child.getAttribute('*for');
        const itemsCommand = /let (.*) of (.*)/.exec(operation);
        if (itemsCommand?.length === 3) {
          const listName = itemsCommand[2];
          const itemName = itemsCommand[1];

          if (rootElement[listName] && Array.isArray(rootElement[listName])) {
            for (let item of rootElement[listName]) {
              const clone = child.cloneNode(true);
              clone.removeAttribute('*for');
              const htmlParts = clone.innerHTML.split('}}');
              htmlParts.forEach((part, i, parts) => {
                const position = part.indexOf('{{');

                if (position >= 0) {
                  const pathTovalue = part
                    .substring(position + 2)
                    .replace(/ /g, '');
                  const prefix = part.substring(0, position);

                  let finalValue = '';
                  let replaced = false;

                  if (pathTovalue.indexOf('.') >= 0) {
                    const byPatternSplitted = pathTovalue.split('.');
                    if (byPatternSplitted[0] === itemName) {
                      replaced = true;
                      for (const subpath of byPatternSplitted) {
                        finalValue = item[subpath];
                      }
                    }
                  } else {
                    if (pathTovalue === itemName) {
                      replaced = true;
                      finalValue = item;
                    }
                  }
                  parts[i] = prefix + finalValue;
                }

                return part;
              });

              clone.innerHTML = htmlParts.join('');

              el.append(clone);
            }
          }
        }
        el.removeChild(child);
      }
      replace(rootElement, child);
    }
  });
}

最后,在组件代码中:

document.addEventListener('DOMContentLoaded', () => {
  const rootElement = document.getElementById('my-list');

  rootElement.contactsList = [
    {
      icon: 'icon-name',
      value: 'item value here',
    },
    ...
  ];

  htmlFor(rootElement);
});

完成。您的普通代码中有一个*for
如果有人想试验一下*for与Angular的*ngFor的性能比较,请与我分享,因为我很好奇。
stackblitz上的代码

相关问题