外部JS文件的行为有所不同

时间:2019-11-16 20:52:53

标签: javascript python html

因此,尽管制作了一个简单的网页来使用python,js和flask-socketio广播动态生成的列表项,但是js代码在引用为外部文件时的行为有所不同,而当以html文件内联编写时,它的工作原理则非常完美。这是代码:

<!DOCTYPE html>
<html>
    <head> 
        <script type="text/javascript" 
        src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>    
        <title>Flack</title>   
        <script>
            document.addEventListener('DOMContentLoaded', () => {
                alert('hello');
                var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);

                socket.on('connect', () => {

                    document.querySelector('#add').onsubmit = () => {
                        var v = document.querySelector('#chname');
                        const channel = v.value;  
                        v.value = '';  
                        socket.emit('add channel', {'channel': channel});                              
                        return false;
                    }
                });

                socket.on('new channel', data => {         
                    const li = document.createElement('li');
                    li.innerHTML = data['channel'];
                    document.querySelector('#channels').append(li);       
                });
            });
        </script>
    </head>
    <body>
        <header>
            <h1>Welcome to Flack</h1>
        </header>
        <p>Join the existing channels or create a new one to have a chit chat with the internet friends.</p>

        <form id= "add">
            <input type="text" autocomplete="off" id="chname" placeholder="Channel Name"/>            
            <button type="submit" id= "submit">Add</button>
        </form>

        <ul id= "channels">
            {% for channel in channels %}
                <li>{{ channel }}</li>
            {% endfor %}
        </ul>

    </body>
</html>

在两种情况下,警报功能都可以正常工作,但是表单操作却不能。是的,我也尝试在body标签的末尾引用我的js文件(../static/index.js)。如果需要的话,这是application.py的代码:

import os
import requests

from flask import Flask, request, render_template, jsonify
from flask_socketio import SocketIO, emit

app = Flask(__name__)
app.config["SECRET_KEY"] = os.getenv("SECRET_KEY")
socketio = SocketIO(app)
channels = []
user = False

@app.route("/")
def index():
    return render_template('index.html', channels=channels)

@socketio.on('add channel')
def add(data):
    channels.append(data['channel'])
    emit("new channel", {'channel': data['channel']}, broadcast=True)

if __name__ == "__main__":
    socketio.run(app, debug= True)

1 个答案:

答案 0 :(得分:0)

这应该有助于您不提交表单

  document.querySelector('#add').onsubmit = (event) => {
                    event.preventDefault();
                    var v = document.querySelector('#chname');
                    const channel = v.value;  
                    v.value = '';  
                    socket.emit('add channel', {'channel': channel});                              
                    return false;
                }

这应该可以解决您的表单无法运行