我有下面的代码,我想在 html 中设置一个变量。由于某种原因,当我删除 JQuery 时,它可以工作,但是当我放入 JQuery 脚本时,它就不能工作。我认为这可能是因为在加载页面时调用了 JQuery,因为如果从按钮调用 JQuery,我就可以让它工作。我尝试过 %s、%(currentDate)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
函数。使用 templating engine 会更好呈现您的 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)
关于javascript - 当包含 JQuery 时,Python 抛出 KeyError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28991578/