【问题标题】:How to pass data into the DOM using querySelector如何使用 querySelector 将数据传递到 DOM
【发布时间】:2019-06-29 09:29:43
【问题描述】:

我正在使用 querySelectorAll 来访问我的 index.html 文件中的 id 和类。我遇到的问题是我试图将数据传递到我的 p.source 类中,该类有两个子跨度,当我使用 innerText 或 innerHTML 时,尽管我的控制台日志显示了数据并没有传递到 DOM要传递到 DOM 的正确数据。您能否帮助我了解发生了什么以及如何将数据传递到该源类中。我是使用 querySelector 的新手,而且 MDN 文档的深度不如我想的那么安静。下面是我的代码。

到目前为止,通过使用控制台,我已经尝试访问 childeNodes 的属性,并且它们可以正常工作,只是让数据反映在 DOM 中

function myQuotes() {
  var quotes = [{
      quote: "Seven billion souls that move around the sun.",
      source: "Childish Gambino",
      citation: "Feels like summer"
    },
    {
      quote: "Don't wait for your world to begin crumbling to make a change.",
      source: "Josh",
      citation: "Past midnight thoughts"
    },
    {
      quote: "The only time we will ever have is right now, no other time exist.",
      source: "Josh",
      citation: "Past midnight thoughts",
      year: 2018
    },
    {
      quote: "Every great developer you know got there by solving problems they were unqualified to solve until they actually did it.",
      source: "Patrick McKenzie",
      citation: "Twitter"

    }
  ];

  console.log('quotes', quotes);

  return quotes;
}

var myQuotesLength = myQuotes().length;
var quotes = myQuotes();

function getRandomQuote(maxNum) {
  var randomNum = Math.floor(Math.random() * maxNum);
  var randomQuote = quotes[randomNum];
  // console.log('random quote', randomQuote );
  return randomQuote;
}



function printQuote() {
  //data call to grab quotes from array of objects
  var message = getRandomQuote(myQuotesLength);
  console.log('message', message);

  //using querySelectors to dynamically pass the data from 'message' into the DOM. Each field works except for sourceField.
  var quoteField = document.querySelectorAll('.quote')[0].innerText = message.quote;
  var source_Parent = document.querySelectorAll('.source');
  console.log('parent', source_Parent);
  var sourceField = source_Parent[0].childNodes[0].innerHTML = message.source;
  console.log('source', sourceField);
  var citationField = source_Parent[0].childNodes[1].innerText = message.citation;
  var yearField = source_Parent[0].childNodes[2].innerText = message.year;
  if (yearField === undefined) {
    yearField = document.getElementsByClassName('year')[0].innerHTML = ' ';
  }
}

document.getElementById('loadQuote').addEventListener("click", printQuote, false);
body {
  background-color: #36b55c;
  color: white;
  font-family: 'Playfair Display', serif;
}

#quote-box {
  position: absolute;
  top: 20%;
  left: 10%;
  right: 10%;
  width: 80%;
  line-height: .5;
}

.quote {
  font-size: 4rem;
  font-weight: 400;
  line-height: 1.1;
  position: relative;
  margin: 0;
}

.quote:before,
.quote:after {
  font-size: 6rem;
  line-height: 2.5rem;
  position: absolute;
}

.quote:before {
  content: "“";
  top: .25em;
  left: -.5em;
}

.quote:after {
  content: "”";
  bottom: -.1em;
  margin-left: .1em;
  position: absolute;
}

.source {
  font-size: 1.25rem;
  ;
  letter-spacing: 0.05em;
  line-height: 1.1;
  text-align: right;
  margin-right: 4em;
}

.source:before {
  content: "—";
}

.citation {
  font-style: italic;
}

.citation:before {
  content: ", ";
  font-style: normal;
}

.year:before {
  content: ", ";
  font-style: normal;
}

#loadQuote {
  position: fixed;
  width: 12em;
  display: inline-block;
  left: 50%;
  margin-left: -6em;
  bottom: 150px;
  border-radius: 4px;
  border: 2px solid #fff;
  color: #fff;
  background-color: #36b55c;
  padding: 15px 0;
  transition: .5s;
}

#loadQuote:hover {
  background-color: rgba(255, 255, 255, .25);
}

#loadQuote:focus {
  outline: none;
}

@media (max-width: 420px) {
  .quote {
    font-size: 2.5rem;
  }
  .quote:before,
  .quote:after {
    font-size: 3rem;
  }
  .source {
    font-size: 1rem;
  }
}
<link href='https://fonts.googleapis.com/css?family=Playfair+Display:400,400italic,700,700italic' rel='stylesheet' type='text/css'>

<div class="container">
  <div id="quote-box">
    <p class="quote">Every great developer you know got there by solving problems they were unqualified to solve until they actually did it.</p>
    <p class="source">Patrick McKenzie<span class="citation">Twitter</span><span class="year">2016</span></p>
  </div>
  <button id="loadQuote">Show another quote</button>
</div>

最终结果是:

-我想将 message.quote 数据传递到quote-box id 的innerHTML(这可行)

-我想把message.source数据传到源类的innerText中(这个不行)

-我想将 message.citation 数据传递到 citation 类的 innerText 中(可行)

-我想将 message.year 数据传递到 year 类的 innerText 中(可行)

【问题讨论】:

  • 这个:message.quote; //鉴于此处显示的代码,无法正确显示 DOM 中的数据。如果有其他代码可以使这项工作,请在您的问题中包含相关代码。
  • @RandyCasburn 请查看代码笔链接以查看完整的代码集。我必须重新格式化它才能解决我的问题,即如何将数据传递到 p 标签中。一切正常。
  • 欢迎来到 SO。强迫某人在场外了解您的问题的基本概念被认为是不好的做法。请始终在您的问题中包含相关代码。该 CodePen 将消失,并且将无法供未来的答案寻求者查看。我敢肯定,您可以想象您的问题现在看起来会多么令人困惑,因为正如问题中所写,message.quote 不可能工作。
  • 知道了,谢谢@RandyCasburn。将更正代码格式。

标签: javascript dom innerhtml selectors-api innertext


【解决方案1】:

问题是您使用的childNodes 也包含文本。

这是来自MDN的注释

childNodes 包括所有子节点,包括非元素节点,如文本和评论节点。要获取仅包含元素的集合,请改用 ParentNode.children

【讨论】:

    【解决方案2】:

    您面临的名称是 childNode,但它不是 .source div 的 childNode,它是 innerText。如果你把名字也放入&lt;span&gt;,它也会变成一个childNode,并且会像一个魅力一样工作。

    这是您的“固定”代码笔,我刚刚在名称周围添加了 &lt;span&gt;https://codepen.io/anon/pen/pGrBEo?editors=1010#0

    或者看看这个工作示例:

    function myQuotes() {
      var quotes = [{
          quote: "Seven billion souls that move around the sun.",
          source: "Childish Gambino",
          citation: "Feels like summer"
        },
        {
          quote: "Don't wait for your world to begin crumbling to make a change.",
          source: "Josh",
          citation: "Past midnight thoughts"
        },
        {
          quote: "The only time we will ever have is right now, no other time exist.",
          source: "Josh",
          citation: "Past midnight thoughts",
          year: 2018
        },
        {
          quote: "Every great developer you know got there by solving problems they were unqualified to solve until they actually did it.",
          source: "Patrick McKenzie",
          citation: "Twitter"
    
        }
      ];
      return quotes;
    }
    
    var myQuotesLength = myQuotes().length;
    var quotes = myQuotes();
    
    function getRandomQuote(maxNum) {
      var randomNum = Math.floor(Math.random() * maxNum);
      var randomQuote = quotes[randomNum];
      return randomQuote;
    }
    
    
    
    function printQuote() {
      var message = getRandomQuote(myQuotesLength);
    
      var quoteField = document.querySelectorAll('.quote')[0].innerText = message.quote;
      var source_Parent = document.querySelectorAll('.source');
      var sourceField = source_Parent[0].childNodes[0].innerHTML = message.source;
      var citationField = source_Parent[0].childNodes[1].innerText = message.citation;
      var yearField = source_Parent[0].childNodes[2].innerText = message.year;
      if (yearField === undefined) {
        yearField = document.getElementsByClassName('year')[0].innerHTML = ' ';
      }
    }
    
    document.getElementById('loadQuote').addEventListener("click", printQuote, false);
    body {
      background-color: #36b55c;
      color: white;
      font-family: 'Playfair Display', serif;
    }
    
    #quote-box {
      position: absolute;
      top: 20%;
      left: 10%;
      right: 10%;
      width: 80%;
      line-height: .5;
    }
    
    .quote {
      font-size: 4rem;
      font-weight: 400;
      line-height: 1.1;
      position: relative;
      margin: 0;
    }
    
    .quote:before,
    .quote:after {
      font-size: 6rem;
      line-height: 2.5rem;
      position: absolute;
    }
    
    .quote:before {
      content: "“";
      top: .25em;
      left: -.5em;
    }
    
    .quote:after {
      content: "”";
      bottom: -.1em;
      margin-left: .1em;
      position: absolute;
    }
    
    .source {
      font-size: 1.25rem;
      ;
      letter-spacing: 0.05em;
      line-height: 1.1;
      text-align: right;
      margin-right: 4em;
    }
    
    .source:before {
      content: "—";
    }
    
    .citation {
      font-style: italic;
    }
    
    .citation:before {
      content: ", ";
      font-style: normal;
    }
    
    .year:before {
      content: ", ";
      font-style: normal;
    }
    
    #loadQuote {
      position: fixed;
      width: 12em;
      display: inline-block;
      left: 50%;
      margin-left: -6em;
      bottom: 150px;
      border-radius: 4px;
      border: 2px solid #fff;
      color: #fff;
      background-color: #36b55c;
      padding: 15px 0;
      transition: .5s;
    }
    
    #loadQuote:hover {
      background-color: rgba(255, 255, 255, .25);
    }
    
    #loadQuote:focus {
      outline: none;
    }
    
    @media (max-width: 420px) {
      .quote {
        font-size: 2.5rem;
      }
      .quote:before,
      .quote:after {
        font-size: 3rem;
      }
      .source {
        font-size: 1rem;
      }
    }
    <link href='https://fonts.googleapis.com/css?family=Playfair+Display:400,400italic,700,700italic' rel='stylesheet' type='text/css'>
    
    <div class="container">
      <div id="quote-box">
        <p class="quote">Every great developer you know got there by solving problems they were unqualified to solve until they actually did it.</p>
        <p class="source"><span>Patrick McKenzie</span><span class="citation">Twitter</span><span class="year">2016</span></p>
      </div>
      <button id="loadQuote">Show another quote</button>
    </div>

    【讨论】:

    • 感谢您对编辑的帮助以及关于 的提示。不会得出这样的结论。所以问题,因为它的 innerText 无论如何都会直接写给它?仅在遇到无法修改 html 的用例时才要求关闭循环。
    • 如果你想直接写入,你可以使用source_Parent[0].innerHTML = message.source + '&lt;span class="citation"&gt;&lt;/span&gt;&lt;span class="year"&gt;&lt;/span&gt;;。请注意,您还必须为引用和年份添加两个 &lt;span&gt;s,因为在这种情况下,您将覆盖整个 &lt;p&gt; 的内部 HTML,而 &lt;span&gt;s 会丢失。
    • 啊,好吧,现在更有意义了。这就是我在尝试getELementsByClassName 时一直遇到的问题,仅当我为&lt;p&gt; 源类设置innerHTML 时,我一直为spans 获得innerHTML = undefined。感谢大佬的洞察力!这个问题困扰了我 48 小时。
    • 不客气。如果我解决了您的问题,请标记为正确答案。 :)
    【解决方案3】:

    您可以使用createTextNodeinsertBefore 方法执行此操作,例如:

    const source = message.source;
    const sourceNode = document.createTextNode(source);
    
    const sourceEl = document.querySelectorAll(".source")[0];
    const citationEl = document.querySelectorAll(".citation")[0];
    
    sourceEl.insertBefore(sourceNode, citationEl);
    

    【讨论】:

      猜你喜欢
      • 2017-11-03
      • 2021-08-26
      • 2011-10-19
      • 2022-07-07
      • 2022-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-14
      相关资源
      最近更新 更多