【发布时间】:2023-03-12 07:30:01
【问题描述】:
嘿,我遇到了以下问题:
我正在构建一个小烧瓶应用程序,通常我只是坚持使用 bootstrap 和 jinja 模板来获得我想要的东西,但这次我需要更多定制的版本。为了掌握知识,我从一个简单的示例开始,该示例使用自定义 js 和烧瓶来获得基本权利。但是让我们详细介绍一下:
假设我在 my_app/ 中有一个名为 app.py 的简单烧瓶 Web 应用程序,如下所示
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(port=8080, debug=True)
而对应的index.html,位于my_app/templates,就是
<!DOCTYPE html>
<html>
<body>
<p>Clicking here will make me dissapear</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<script>
$(document).ready(function() {
$("p").click(function(event){
$(this).hide();
});
});
</script>
</body>
</html>
然后我看到了预期的结果,即我可以点击段落使其消失。
但是:我想将 javascript 部分放入 static/js/ 下的 main.js 文件中。像这样:
$(document).ready(function() {
$("p").click(function(event){
$(this).hide();
});
});
index.html 变成:
<!DOCTYPE html>
<html>
<body>
<p>Clicking here will make me dissapear</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src='/js/main.js'></script>
</body>
</html>
不幸的是,什么都不会发生。我也尝试过其他引用脚本文件的方法,但直到现在没有任何效果。我的印象是我错过了一些非常简单的东西。提前致谢!
【问题讨论】:
-
当您在浏览器中点击该 URL“/js/main.js”(直接在搜索栏中输入)时,该文件是否存在?
-
嗨 Josh,我可以在 127.0.0.1:8080/static/js/main.js 下看到它。因为据我所知,Flask 在静态文件夹中查找此类文件,我认为这需要省略。显然我错了。
标签: javascript python flask