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
bodyvariable: You first assigned the post's body text tovar body, then immediately reused the same variable name to store the split position. This overwrote the actual text content you need to split! - Undefined
strvariable: You tried to usestr.lengthandstr.slice()but never declared or assignedstr—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
postBodyso 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
相关产品推荐
相关产品推荐

