簡體   English   中英

從 .txt 文件中取出一行並顯示在 html 頁面中

[英]Take line from .txt file and display in html page

我想為我的女朋友做一個小項目,我的想法是有一個 HTML 頁面,上面寫着“我愛”。 按下按鈕后,網站將在文本下方顯示我制作的文本文檔中的隨機一行,其中包含我喜歡的關於她的所有內容。 示例:我管理的

所以我設法制作了一個只有“我愛”的頁面,並在我點擊按鈕時在它下面添加了文本。 但我希望它能夠從 .txt 文件中隨機抽取一行,其中每一行都是一行文本,它會隨機選擇並顯示在 html 上。 謝謝

您不能從客戶端從服務器上的文件加載,因為這在安全性方面是一個巨大的禁忌。 想象一下。 您需要一些后端(服務器端)語言,如 PHP。

這是最基本的 PHP 代碼(帶注釋),可以滿足您的需求:

<?php
// you put your filename here ( obviously )
$fileName = "girl.txt";

// opening and reading file
$fileH = fopen( $fileName, "r") or die("Unable to open file!");
$fileCont = fread( $fileH,filesize( $fileName));
fclose($fileH);

// split text into lines
$lines = explode( "\r\n", $fileCont);
$numOfLines = count($lines);

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <!-- import math module -->
    <script src=https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.3.0/math.min.js></script>
</head>
<body>
    <!-- prints random choice to html code -->
    <h1>I Love</h1>
    <button>Click Me!</button>
    

    <script>
        // print php array into js
        <?php echo "lines = ['".join("', '", $lines)."'];\n"; ?>
        maxLineNum = <?php echo $numOfLines; ?>;

        // on button click you get random msg in h1
        document.querySelector("button").addEventListener( "click", ()=>{
            randNum = math.floor( math.random()*maxLineNum );
            document.querySelector("h1").textContent = "I love " + lines[randNum];
        } );

    </script>
</body>
</html>

我是 JavaScript 的新手,但我會嘗試將片段存儲在 JS 本身的數組中,而不是將它們放在單獨的文本文件中,然后在使用之前需要訪問和處理。

JS:

const niceSnippets = [
  ‘your smile’,
  ‘your sense of humour’, // repeat for as many snippets as you can think of
  ‘you’
];

const chooseSnippet = () => { niceSnippets[Math.floor(Math.random()*niceSnippets.length)]; }

const changeSnippet = () => { document.getElementById('snippetDisplay').innerText = chooseSnippet(); }

使用 id 和 onclick 更新 HTML 中的相關元素:

<p id=“snippetDisplay”></p>
<button onclick=“changeSnippet()”>Click Me!</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM