Python 在包含 JQuery 时抛出 KeyError
Python throwing KeyError when JQuery included
我有下面的代码,我想在html中设置一个变量。出于某种原因,当我删除 JQuery 时,它可以工作,但是当我放入 JQuery 脚本时,它不起作用。我认为这可能是因为在加载页面时调用了 JQuery,因为如果从按钮调用 JQuery,我可以让它工作。我已经尝试了 %s、%(当前日期)s、{0} 然后是它们的相关输出,但它们似乎都没有奏效。前两个抛出ValueError: unsupported format character ''' (0x27) at index 952
,然后{0}导致KeyError: "'n $('"
class Fitbit(object):
@cherrypy.expose
def index(self):
currentDate = (time.strftime("%d/%m/%Y"))
return """<html>
<head>
<title>Fitbit</title>
<link href="/static/css/fitbit.css" rel="stylesheet">
<script>
$('document').ready(init);
function init(){
$('.bar-percentage[data-percentage]').each(function () {
var progress = $(this);
var percentage = Math.ceil($(this).attr('data-percentage'));
$({countNum: 0}).animate({countNum: percentage}, {
duration: 2000,
easing:'linear',
step: function() {
// What todo on every count
var pct = '';
if(percentage == 0){
pct = Math.floor(this.countNum) + '%';
}else{
pct = Math.floor(this.countNum+1) + '%';
}
progress.text(pct) && progress.siblings().children().css('width',pct);
}
});
});
};
</script>
</head>
<body>
<h4>{0}</h4>
</body>
</html>""" .format(currentDate)
#return html
index.exposed = True
如果我删除 JQuery,它肯定工作正常并显示日期。任何其他尝试的想法将不胜感激。
由于JavaScript中的所有大括号,您遇到了问题。这会混淆format
函数。最好使用模板引擎来渲染 HTML。
但是,如果您想继续使用当前代码,请尝试将 JavaScript/jQuery 代码放入其自己的变量中,然后通过format
调用将其插入到 HTML 中。
currentDate = (time.strftime("%d/%m/%Y"))
javascript = """
$('document').ready(init);
function init(){
$('.bar-percentage[data-percentage]').each(function () {
var progress = $(this);
var percentage = Math.ceil($(this).attr('data-percentage'));
$({countNum: 0}).animate({countNum: percentage}, {
duration: 2000,
easing:'linear',
step: function() {
// What todo on every count
var pct = '';
if(percentage == 0){
pct = Math.floor(this.countNum) + '%';
}else{
pct = Math.floor(this.countNum+1) + '%';
}
progress.text(pct) && progress.siblings().children().css('width',pct);
}
});
});
};
"""
return """<html>
<head>
<title>Fitbit</title>
<link href="/static/css/fitbit.css" rel="stylesheet">
<script>{0}</script>
</head>
<body>
<h4>{1}</h4>
</body>
</html>""".format(javascript, currentDate)
相关文章:
- 无法从 jQuery RSS Feed 中的 localStorage 动态替换类
- 如何使用jQuery自动打开页面上的所有链接
- 如何使用jquery在填充自动完成的值后使文本框只读
- jQuery:循环一个具有不同超时值的循环
- 用程序搜索JQuery数据表中的文本
- 使用 jQuery 的 .on 函数如何获取事件的原始元素
- jQuery匹配JSON对象的部分文本
- Jquery POST未填充数组
- JQuery使计数器每次更改时都会增加
- 如何在Angular2中使用jQuery插件
- 提高JQuery的性能
- 无法在通过jQuery的ajax加载的页面中执行javascript
- JQuery合并了keyup和focusout两个函数
- 如何使用jQuery选择下拉列表的值
- 将PHP变量传递给jQuery时遇到问题
- jQuery UI自动完成突然停止工作
- 剑道网格jQuery动画()问题
- 如何使jQuery插件函数可调用以供独立使用,而不在集合上操作
- jquery点击函数select&取消选择
- Python 在包含 JQuery 时抛出 KeyError