You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中拆分字符串变量内容并分别输出至两个div的方法

Fixing Your JSON Fetch & Text Splitting Code

Let's get your code working smoothly—you've got the right idea with fetching the post and splitting the body, just a couple of small bugs holding you back. Here's what was going wrong, plus a fully fixed version:

Key Issues in Your Original Code

  • Duplicate body variable: You first assigned the post's body text to var body, then immediately reused the same variable name to store the split position. This overwrote the actual text content you need to split!
  • Undefined str variable: You tried to use str.length and str.slice() but never declared or assigned str—you meant to use the post's body text here.
  • Missing output for split content: You set the title but didn't add code to render the two split body parts into your divs.

Fixed Code

function req1() {
  fetch('https://jsonplaceholder.typicode.com/posts/1')
    .then(function(res) {
      return res.json();
    })
    .then(function(json) {
      // Grab the title and body from the JSON response
      var title = json.title;
      var postBody = json.body; // Renamed to avoid conflict with split position

      // Calculate where to split the body text (halfway point, rounded up)
      var splitPoint = Math.ceil(postBody.length / 2);

      // Split the body into two parts
      var s1 = postBody.slice(0, splitPoint);
      var s2 = postBody.slice(splitPoint);

      // Update the DOM elements with the content
      document.getElementById("newsTitle").innerHTML = title;
      // Make sure these divs exist in your HTML!
      document.getElementById("newsBodyPart1").innerHTML = s1;
      document.getElementById("newsBodyPart2").innerHTML = s2;
    })
    // Add error handling in case the fetch fails
    .catch(function(error) {
      console.error('Error fetching data:', error);
    });
}

// Don't forget to call the function!
req1();

Quick Notes

  • I renamed the original body variable to postBody so we don't overwrite it when calculating the split position
  • Added error handling with .catch() to debug any fetch issues
  • Make sure your HTML has the three required divs:
    <div id="newsTitle"></div>
    <div id="newsBodyPart1"></div>
    <div id="newsBodyPart2"></div>
    

内容的提问来源于stack exchange,提问作者Crashy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:59:09