При вводе чисел в текстовое поле для получения историй все работает нормально, пока я не наберу цифру «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.info('Generated text element not found.');
}
var contentWrapper = document.getElementById('content-wrapper');
if (contentWrapper) {
contentWrapper.style.marginTop = '60px';
} else {
console.info('Content wrapper element not found.');
}
currentStory = storyNumber;
} else {
console.info('Story container element not found.');
}
} else {
console.info('Error fetching story. Status code: ' + xhr.status);
clearStoryContainer();
displayErrorMessage('Error fetching story.');
}
};
xhr.onerror = function () {
console.info('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.';
}
?>
истории.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.
Почему это происходит? Нужно ли мне что-то менять?



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


В функции displayErrorMessage вы используете InternalHTML для контейнера истории. При загрузке сообщения об ошибке элемент div с id="generated-text" будет заменен, поэтому, когда вы попытаетесь снова показать одну историю, не будет элемента div с id="generated-text" для отображения истории.
Вам просто нужно показать сообщение об ошибке в сгенерированном тексте или использовать другой div.
function displayErrorMessage(errorMessage) {
var storyContainer = document.getElementById('story-container');
storyContainer.style.display = 'block';
var generatedTextElement = document.getElementById('generated-text');
generatedTextElement.innerHTML = errorMessage;
document.getElementById('content-wrapper').style.marginTop = '60px';
currentStory = null;
}
история.txt
1. [[IDAHO: The Bear Lake Monster]]
...............................
###2. [[DELAWARE: The Addy-Sea Inn]]
..................................
###3. [[Inn of the Goblin]]
...................................
Что было бы хорошим способом изменить это?
Думаю, мне удалось это исправить. Но теперь есть следующая проблема: первая история генерируется нормально, но затем следующая история генерируется немного ниже, оставляя довольно много места вверху.
Я отредактирую свой ответ, заменю отправленную мной функцию displayErrorMessage на вашу, и проблема будет решена.
Да, это помогло! Но теперь есть следующая проблема: первая история генерируется нормально, но затем следующая история генерируется немного ниже, оставляя довольно много места вверху. А затем третий идет еще ниже.
Поскольку в вашем файле Story.txt вы используете 1 новую строку для истории 2 и 2 новой строки для истории 3, для решения проблемы вам придется удалить новые строки из историй.
Что вы подразумеваете под «удалением новой строки»?
Я редактирую свой ответ, видел часть Story.txt. Вам придется редактировать свои истории вот так, чтобы убрать лишние строки.
Дело в том, что мне нужны пустые строки, чтобы превратить их в абзацы.
Просто удалите новую строку после ### и перед номером. Также было бы неплохо, если бы мой ответ был выбран в качестве окончательного.
Я новичок в Stack Overflow, поэтому не знаю, как это сделать. Кроме того, когда я сейчас нажимаю любую кнопку, кажется, что на секунду или около того возникает какой-то эффект мигания, есть идеи, что вызывает это?
Вы это сделали и ответ выбран, спасибо. Кроме того, мой последний комментарий решил вашу проблему?
Не совсем, но я нашел исправление в PHP. Но проблема с миганием все еще существует: он мигает на секунду всякий раз, когда я нажимаю любую кнопку для создания истории.
Чтобы исправить это, вы можете изучить и использовать jQuery и функцию обратного вызова для управления каждым движением в браузере.
Мне потребовалось бы довольно много времени, чтобы изучить jQuery и функции обратного вызова, поэтому, если бы вы могли мне в этом помочь, я был бы очень, очень благодарен!
Конечно, но вам нужно открыть новый вопрос и описать, чего вы хотите.
Проблема решена, но удалить вопрос невозможно.
Вам не нужно удалять этот вопрос, он останется для будущих пользователей, у которых может возникнуть такая же проблема.
Каким-то образом мне запретили создавать новые вопросы, и я не знаю, как это решить:/
Это потому, что ты задаешь слишком много вопросов! Обычно вам придется покопаться и через пару дней, если ничего не получится, попытаться отправить новый вопрос.
Это проблема JS, проблема PHP, проблема HTML или проблема CSS?