繁体   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