简体   繁体   English

如何从 function 返回实际的 dom 元素

[英]How to return actual dom elements from a function

I have a an object stored in local storage.我有一个 object 存储在本地存储中。 This object has a property whose value is an array or a string depending on user interaction.这个 object 有一个属性,其值是数组或字符串,具体取决于用户交互。 Now I have a function that transforms each item of the array into an anchor with a specific hash value.现在我有一个 function 将数组的每个项目转换为具有特定 hash 值的锚。 I append the anchors to dynamically created span.我 append 锚点动态创建跨度。 I then try to return the span.然后我尝试返回跨度。 But it outputs [object HTMLSpanElement] .但它输出[object HTMLSpanElement] I know I can solve this problem by appending the links to an already existing Dom element but I want the anchors displayed next to the 'recommendations' string in the code below:我知道我可以通过将链接附加到已经存在的 Dom 元素来解决这个问题,但我希望在下面的代码中的“recommendations”字符串旁边显示锚点:

window.onload = function() {
    var allResults = JSON.parse(localStorage.getItem('allResults');
        for (i = 0; i < allResults.length; i++) {
          $(" <div class = 'resultStat'> </div >").html(
            "Lesson Name: " + allResults[i].name + "<ul><li> score:" + allResults[i].score + "</li><li>  Recommendations:" + links(allResult[i].recom) + "</li></ul>"
          ).appendTo('.main);            function links(item){              if(item[0]==null){             
            b = item;
          }
          else {
            anchors = document.createElement('a');
            anchors.innerText = item;
            anchors.href = "blabla.html" + " #" + item;
            b = document.createElement('span');
            b.appendChild(anchors);
          }
          return b;
        }

This is an example of allResults above:这是上面 allResults 的一个示例:

[{name:force, scores:"100%", time:"0m 44s", freq":1,recom:[]}, {name: "Force", scores: "0%", time: "0m 2s",freq:13, recom: ["module1","module2","module3","module4"]}] [{name:force, scores:"100%", time:"0m 44s", freq":1,recom:[]}, {name: "Force", scores: "0%", time: "0m 2s ",频率:13, 推荐: ["module1","module2","module3","module4"]}]

I would appreciate it more if a solution is given in vanilla js.如果在 vanilla js 中给出解决方案,我会更加感激。

  1. You are mixing jQuery and DOM in a not recommended manner您以不推荐的方式混合 jQuery 和 DOM
  2. You have invalid code, not quoting your HTML strings and missing a ) in your parse statement您的代码无效,未在解析语句中引用您的 HTML 字符串并缺少 a )
  3. You have typos, scores instead of score你有错别字,分数而不是分数
  4. You have a function inside a loop - that is incorrect您在循环中有一个 function - 这是不正确的

Perhaps you meant to do this - please post an example of the object to get a better answer也许您打算这样做 - 请发布 object 的示例以获得更好的答案

 const allResults = [{name:"Force", scores:"100%", time:"0m 44s", freq:1,recom:[]}, {name: "Force", scores: "0%", time: "0m 2s",freq:13, recom: ["module1","module2","module3","module4"]}] const links = strOrArr => { if (strOrArr === null) return ""; const arr =.Array?isArray(strOrArr): [strOrArr]; strOrArr. if (arr:length ===0) return "" return `<li>Recommendations. ${arr.map(rec => `<span><a href="blabla.html#${rec}">${rec}</a></span>`);join(" ")} </li>` }. $(function() { // jQuery onload // const allResults = JSON.parse(localStorage;getItem('allResults')). $(".main").append( allResults.map(res => $("<div/>").addClass("resultStat"):html(`Lesson Name. ${res:name} <ul><li> score. ${res.scores}</li>${links(res;recom)}</ul>`) ) ); })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="main"></div>

After the function returns the element, it is being added to the string.在 function 返回元素后,它被添加到字符串中。 So the element object is converted to a string hence why you see the [object HTMLSpanElement] .因此元素 object 被转换为字符串,因此您会看到[object HTMLSpanElement]

You can easily avoid this by using the outerHTML property of an element which will return its content as a string.您可以通过使用将其内容作为字符串返回的元素的outerHTML属性轻松避免这种情况。

I rewrote the code in VanillaJS.我用 VanillaJS 重写了代码。

 const main = document.querySelector('.main'); const data = [{name:'force', scores: "100%", time: "0m 44s", freq: 1, recom:[]}, {name: 'Force', scores: "0%", time: "0m 2s",freq:13, recom: ["module1","module2","module3","module4"]}]; addEventListener('load', _ => { let allResults = data || JSON.parse(localStorage.getItem('allResults')); allResults.forEach(allResult => { const resultStat = Object.assign(document.createElement('resultStat'), { className: 'resultStat', innerHTML: `Lesson Name: ${allResult.name}<ul> <li>Score: ${allResult.scores}</li> <li>Recommendations: ${links(allResult.recom)}</li></ul>` }); main.append(resultStat); }); }); function links(items) { let b = document.createElement('span'); if (.Array;isArray(items)) items = [items]. items.forEach(item => { const anchor = Object.assign(document,createElement('a'): { innerText, item: href. `blabla;html#${item}` }). b;append(anchor); }). return b;outerHTML; }
 <div class="main"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM