当输入数字到文本框中以获取故事时,它工作得很好,直到我输入数字“4”,点击“获取故事”按钮,并尝试回到数字3。这时,我在控制台窗口的第35行看到了这条消息:
“未找到生成的文本元素。”
HTML:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Story Fetcher</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>Stories</h1>
</header>
<main>
<div id="content-wrapper">
<div id="get-container">
<input type="text" id="story-number" placeholder="Enter story number">
<button id="get">Get Story</button>
<button id="getRandom">Random Story</button>
</div>
<div id="story-container">
<div id="generated-text"></div>
<button id="clear">Clear</button>
</div>
</div>
</main>
<script src="script.js"></script>
</body>
</html>
CSS:
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
margin: 0;
padding: 0;
}
header {
background-color: #ff6600;
color: #fff;
padding: 20px;
text-align: center;
}
h1 {
font-size: 28px;
margin: 0;
}
main {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 80vh;
}
#content-wrapper {
background-color: #fff;
border-radius: 4px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
padding: 20px;
max-width: 100%;
text-align: center;
margin: 20px;
overflow-x: hidden;
}
#story-number {
padding: 10px 16px;
font-size: 14px;
border: 1px solid #ccc;
border-radius: 4px;
width: 200px;
height: 30px;
margin-bottom: 10px;
}
#get-container {
display: flex;
flex-direction: column;
align-items: center;
}
#get, #getRandom, #clear {
background-color: #ff6600;
color: #fff;
border: none;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
border-radius: 4px;
transition: background-color 0.3s ease;
margin-bottom: 10px;
}
#story-container {
background-color: #fff;
border-radius: 4px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
padding: 20px;
max-width: 100%;
text-align: center;
display: none;
}
#generated-text {
font-size: 18px;
line-height: 1.5;
margin-bottom: 20px;
color: #333;
text-align: center;
}
#generated-text span {
font-weight: bold;
color: #000;
font-size: 20px;
}
#clear {
display: block;
margin: 0 auto;
}
@media (min-width: 601px) {
#content-wrapper {
max-width: 600px;
max-height: 40vh;
}
}
@media (max-width: 600px) {
#get, #clear {
font-size: 10px !important;
padding: 20px 20px !important;
}
}
JavaScript:
document.addEventListener('DOMContentLoaded', function () {
var totalStories = 3;
var currentStory = null;
function clearStoryContainer() {
var storyContainer = document.getElementById('story-container');
if (storyContainer) {
storyContainer.style.display = 'none';
var generatedTextElement = document.getElementById('generated-text');
if (generatedTextElement) {
generatedTextElement.innerHTML = '';
}
var contentWrapper = document.getElementById('content-wrapper');
if (contentWrapper) {
contentWrapper.style.marginTop = '0';
}
currentStory = null;
}
}
function fetchStory(storyNumber) {
clearStoryContainer();
var xhr = new XMLHttpRequest();
xhr.open('GET', 'fetch.php?story=' + storyNumber, true);
xhr.onload = function () {
if (xhr.status === 200) {
var storyContainer = document.getElementById('story-container');
if (storyContainer) {
storyContainer.style.display = 'block';
var generatedText = xhr.responseText;
var generatedTextElement = document.getElementById('generated-text');
if (generatedTextElement) {
generatedTextElement.innerHTML = parseAndStyleTitles(generatedText);
} else {
console.log('Generated text element not found.');
}
var contentWrapper = document.getElementById('content-wrapper');
if (contentWrapper) {
contentWrapper.style.marginTop = '60px';
} else {
console.log('Content wrapper element not found.');
}
currentStory = storyNumber;
} else {
console.log('Story container element not found.');
}
} else {
console.log('Error fetching story. Status code: ' + xhr.status);
clearStoryContainer();
displayErrorMessage('Error fetching story.');
}
};
xhr.onerror = function () {
console.log('Network error while fetching story.');
clearStoryContainer();
displayErrorMessage('Network error while fetching story.');
};
xhr.send();
}
function displayErrorMessage(errorMessage) {
var storyContainer = document.getElementById('story-container');
storyContainer.style.display = 'block';
storyContainer.innerHTML = errorMessage;
document.getElementById('content-wrapper').style.marginTop = '60px';
currentStory = null;
}
function parseAndStyleTitles(text) {
return text.replace(/\[\[(.*?)\]\]/g, function (match, title) {
return '<span>' + title + '</span>';
});
}
document.getElementById('get').addEventListener('click', function () {
var storyNumber = parseInt(document.getElementById('story-number').value);
if (!isNaN(storyNumber) && storyNumber >= 1 && storyNumber <= totalStories) {
fetchStory(storyNumber);
} else {
displayErrorMessage('Please enter a valid number between 1 and ' + totalStories + '.');
}
});
document.getElementById('getRandom').addEventListener('click', function () {
var randomStoryNumber = Math.floor(Math.random() * totalStories) + 1;
fetchStory(randomStoryNumber);
});
document.getElementById('clear').addEventListener('click', function () {
clearStoryContainer();
});
});
PHP:
<?php
// Read the requested story number from the URL parameter
$storyNumber = $_GET['story'];
// Check if the story number is valid (e.g., within the range of available stories)
$totalStories = 3; // Update this to match the actual total number of stories
if ($storyNumber >= 1 && $storyNumber <= $totalStories) {
// Read the content of stories.txt
$storiesFile = file_get_contents('stories.txt');
// Split the content into stories based on a unique delimiter (e.g., "###")
$stories = explode("###", $storiesFile);
// Get the requested story
$requestedStory = trim($stories[$storyNumber - 1]); // Adjust the array index
// Replace newline characters with <br> tags for line breaks
$formattedStory = nl2br($requestedStory);
// Return the formatted story as a response
echo $formattedStory;
} else {
// Return an error message if the story number is invalid
echo 'Error: Invalid story number.';
}
?>
stories.txt
1. [[IDAHO: The Bear Lake Monster]]
In the depths of Bear Lake, a legend born from Joseph C. Rich's pen lurks—a tale of the enigmatic "Bear Lake Monster." This 20th-century legend, chronicled by Rich, tells of an elusive creature with sightings of a colossal, malevolent "water devil." Its elongated neck, capable of striking from the water's edge, added to its mystique.
Through generations, tales of the Bear Lake Monster echoed in the region, whispered around campfires and passed down. The lake's murky depths became a realm of fear and fascination, where the line between reality and legend blurred.
Recent events added a twist—a 25-foot-long decomposed carcass found on the lake's shores. Some claim it to be the creature of centuries-old sightings, sparking intrigue and mystery.
The legend of the Bear Lake Monster, rooted in both the written word and local memory, continues to cast its eerie shadow over the tranquil waters of the lake, serving as a reminder of the enduring allure of the unknown and the power of myth in the human experience.
### <!-- Unique delimiter separating stories -->
2. [[DELAWARE: The Addy-Sea Inn]]
Nestled on Bethany Beach's serene shores, the Addy-Sea Inn, dating back to 1902, exudes timeless elegance and history. Yet, beneath its historic exterior lies a tapestry of paranormal encounters and unexplained phenomena.
Three specific rooms within the inn are rumored to house restless spirits. In Room 1, guests have reported the antique porcelain tub shaking mysteriously during baths, as though stirred by unseen hands. Room 6 resonates with ethereal organ music despite the absence of instruments, creating an enchanting yet enigmatic atmosphere.
Room 11, however, emerges as the epicenter of these ghostly tales, rumored to be haunted by the spirit of Paul Dulaney, the inn's former handyman. His spectral presence occasionally materializes near the bed, blurring the boundaries between the living and the departed.
As guests step into the historic Addy-Sea Inn, they anticipate encounters with the spectral. Within its hallowed halls, the living and the otherworldly intersect, offering a unique opportunity to commune with the spirits of yesteryear and engage in the timeless dance between the seen and the unseen.
### <!-- Unique delimiter separating stories -->
3. [[Inn of the Goblin]]
Nestled on Bethany Beach's serene shores, the Addy-Sea Inn, dating back to 1902, exudes timeless elegance and history. Yet, beneath its historic exterior lies a tapestry of paranormal encounters and unexplained phenomena.
Three specific rooms within the inn are rumored to house restless spirits. In Room 1, guests have reported the antique porcelain tub shaking mysteriously during baths, as though stirred by unseen hands. Room 6 resonates with ethereal organ music despite the absence of instruments, creating an enchanting yet enigmatic atmosphere.
Room 11, however, emerges as the epicenter of these ghostly tales, rumored to be haunted by the spirit of Paul Dulaney, the inn's former handyman. His spectral presence occasionally materializes near the bed, blurring the boundaries between the living and the departed.
As guests step into the historic Addy-Sea Inn, they anticipate encounters with the spectral. Within its hallowed halls, the living and the otherworldly intersect, offering a unique opportunity to commune with the spirits of yesteryear and engage in the timeless dance between the seen and the unseen.
为什么会发生这种情况?我需要改变什么吗?
1条答案
按热度按时间eulz3vhy1#
在displayErrorMessage函数中,您使用innerHTML作为story-container。当错误消息加载时,id=“generated-text”的div将被替换,因此当您尝试再次显示一个故事时,没有id=“generated-text”的div来显示该故事。
你只需要在生成的文本中显示错误信息或使用另一个div。
story.txt