包含JQuery时Python抛出KeyError

2024-09-27 07:27:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的代码,我想在html中设置一个变量。由于某些原因,当我删除JQuery时,它可以工作,但是当我放入JQuery脚本时,它就不能工作了。我想这可能是因为JQuery是在加载页面时被调用的,因为如果JQuery是从按钮调用的,我可以让它工作。我尝试过%s、%(currentDate)s、{0}以及它们相关的输出,但似乎都没有起作用。前两个抛出ValueError: unsupported format character ''' (0x27) at index 952,然后{0}导致{}

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,它肯定可以正常工作并显示日期。任何其他的想法,尝试什么将不胜感激。在


Tags: formatindexvarhtmlfunctionmathjquerythis
1条回答
网友
1楼 · 发布于 2024-09-27 07:27:20

您遇到了一个问题,因为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)

相关问题 更多 >

    热门问题