簡體   English   中英

將表單添加到我的 HTML 會使 Javascript 文件中的 Function 無法正常工作

[英]Adding a Form into My HTML Keeps Function in Javascript File from Working

由於某些莫名其妙的原因,每當我在塊引用上方的三行周圍添加<form></form>時,塊引用內的文本停止被從 flask 服務器返回的文本替換。 我沒有任何需要解決的問題,因為我可以輕松解決這個問題。 我只是好奇為什么這個問題首先存在。

HTML:

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="{{ url_for('static', filename='CSSsheets/SBPstyle.css') }}" />
    <title></title>
</head>
<body>
    <input id="expertiseReq" placeholder="leave blank for any skill level" />
    <input id="locationReq" placeholder="leave blank for any location" />
    <button id="gatherNames">Click to Get List of Player Names</button> 
    <blockquote id="playerNamesGoHere" class="properly_sized_blockquote">No Player Names Loaded</blockquote>
    <script src="{{ url_for('static', filename='JSscripts/SBPscript.js') }}"></script>
</body>
</html>

CSS:

.properly_sized_blockquote {
    border: solid;
    border-block-width: 20px;
    height: 600px;
    width: 150px;
}

JavaScript:

const gatherPlayersButton = document.getElementById('gatherNames');
const areaForPlayerNames = document.getElementById('playerNamesGoHere')
const summon_players = () => {
    let eR
    let lR
    if (document.getElementById('expertiseReq').value == "") {
        eR = "None";
    } else {
        eR = document.getElementById('expertiseReq').value
    };
    if (document.getElementById('locationReq').value == "") {
        lR = "None";
    } else {
        lR = document.getElementById('locationReq').value
    };
    let tagsString = eR + "," + lR;
    fetch(`/battle?tags=${tagsString}`, { method: "GET" }).then((response) => response.text()).then((text) => {
        areaForPlayerNames.innerText = text;
    });
};

gatherPlayersButton.addEventListener("click", () => summon_players());

Flask 服務器:

from flask import Flask, render_template, request
from static.SNEKfiles import SpaceShipGame
import json


game_app = Flask(__name__)

@game_app.route('/') 
@game_app.route('/home')
def home():
    return render_template("HTMLPage1.html")

@game_app.route('/battle', methods=['GET', 'POST'])
def battle():
    if request.method == 'GET':
        gathering_player_requirements = request.args.get('tags')
        if gathering_player_requirements != None:
            print(gathering_player_requirements)
            skill_requirement = gathering_player_requirements.split(",")[0]
            location_requirement = gathering_player_requirements.split(",")[1]
            gathering_player = SpaceShipGame.Player()
            gathered_player_names = gathering_player.obtainAllPlayerNames(skill_requirement, location_requirement)
            return gathered_player_names
        else:
            return render_template("SingleBattlePage.html")

按鈕默認為type="submit" 當您添加<form>時,除了觸發其點擊處理程序之外,該按鈕突然有一個要提交的表單。

考慮:

 document.querySelector("form").addEventListener("submit", e => { e.preventDefault(); console.log("form submitted"); }); document.querySelectorAll("button").forEach(e => e.addEventListener("click", e => console.log("button clicked") ) );
 form { background: red; padding: 1em; margin-bottom: 1em; }
 <form> <button>Submit and trigger click</button> </form> <button>Outside of form--just click</button>

雖然尚不清楚您添加的<form>元素是什么樣的(它的methodaction屬性是什么?),但聽起來您只是想了解一下場景,所以希望這已經足夠了。 type="button"添加到按鈕將阻止它觸發表單提交,因此您之前的任何行為都應該保持不變。

 document.querySelector("form").addEventListener("submit", e => { e.preventDefault(); console.log("form submitted"); }); document.querySelectorAll("button").forEach(e => e.addEventListener("click", e => console.log("button clicked") ) );
 form { background: red; padding: 1em; margin-bottom: 1em; }
 <form> <button type="button"> Inside of form--trigger click only since type="button" was added </button> </form> <button>Outside of form--just click</button>

請參閱HTML 中的按鈕類型:這就是為什么您應該始終聲明它以了解詳細信息。


減少代碼異味和遵守最佳實踐的其他一些建議:

  • 對 CSS 類和 id 使用 kebab kebab-case (或至少保持一致)。
  • 對 JS 函數和變量使用camelCase
  • 對 Python 函數和變量使用snake_case
  • 避免在整個模板中內聯注入腳本片段。 如果可能,請使用模塊並在文檔末尾加載腳本。 這使 HTML 和 JS 保持分離,並確保在開始操作之前完全加載 DOM。 所有這些都應該使調試更容易。
  • 在腳本周圍使用閉包來防止變量名沖突。
  • 當你可以重構為const時避免let const提供了更強大的重新分配保證,並且通常使邏輯更易於理解和調試。
  • 使用===而不是==來避免由於類型強制導致的奇怪誤報。
  • 避免使用連接或其他自定義分隔符構建查詢字符串有效負載: let tagsString = eR + "," + lR; . 使用類似encodeURIComponent的東西到單獨的參數中,或者將路由切換到 POST 並使用 JSON 有效負載。 如果用戶提供逗號,您的代碼可能會出現異常。
  • 檢查所有fetch調用的響應以確保它正常,如果不是,則處理任何錯誤。
  • 文件夾、文件和 HTML 頁面應為小寫。

暫無
暫無

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

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