js添加事件监听器无法正常工作

时间:2018-02-11 01:19:24

标签: javascript dom addeventlistener

我正在尝试将问题'array(q)中的一些questins交互加载到我的页面中,并且在学生点击其中一个问题之后注册答案并使用js while循环更改问题。我的错误是什么不起作用?

import re
from products.models import Category, Brands
from django.core.management.base import BaseCommand


class Command(BaseCommand):
    help = "Load some sample data into the db"

    def add_arguments(self, parser):
        parser.add_argument('--file', dest='file', help='File to load')

    def handle(self, **options):
        from products.models import Product, Category
        all_categories = list(Category.objects.all())

        if options['file']:
            print("Importing " + options['file'])

            with open(options['file']) as f:
                linecount = 0
                next(f)
                for line in f:
                    linecount += 1
                    fields = line.split(',')
                    category = Category.objects.get_or_create(name=fields[10])
                    brand_name = Brands.objects.get_or_create(brand_name=fields[7])

                    data = {
                            'aw_deep_link':  fields[0],
                            'description': fields[1],
                            'product_name': fields[2],
                            'aw_image_url':  fields[3],
                            'search_price':  fields[4],
                            'merchant_name': fields[5],
                            'display_price':  fields[6],
                            'brand_name':  brand_name[0],
                            'colour' :  fields[8],
                            'rrp_price' :  fields[9],
                            'category' :  category[0],

                    }

                    for textfield in ('description', 'product_name'):
                        # I suppose these are the two relevant fields to scan?
                        subcat = None
                        for cat in all_categories:
                            if re.search(cat.regex, data[textfield]) is not None:
                                if cat.is_leaf_node():
                                    # only consider nodes that have no children
                                    subcat = cat
                                    break
                        if subcat is not None:
                            break
                    # subcat is now the first matching subcategory
                    if subcat is not None:
                        data['category'] = subcat

                    product = Product(**data)
                    product.save()

                print("Added {0} products".format(linecount))

2 个答案:

答案 0 :(得分:1)

事件侦听器是异步执行的,您编写的代码可能假定侦听器可以阻止循环执行。 要解决此问题,请尝试删除循环并将切换到下一个问题的逻辑移动到侦听器回调中。

答案 1 :(得分:1)

你的while循环无休止地循环,因为逻辑上唯一的东西就是将toNext设置为False,设置一些事件监听器回调,然后再次评估toNext,这将始终为False。因此永远不会调用i++i < q.length将始终为True。

摆脱while循环。编写一个单独的函数来评估答案并使用下一个问题更新窗口。将该函数用作click事件的回调。 在回调函数中,this将被设置为调用该函数的对象,因此您可以编写如下函数:

function callback() {
    if (this.id == q[i][0]) {
        window.correct++;
    } else {
        window.incorrect++;
    }

    i++;

    set_question(i); // Logic to set the i-th question.
}

修改

function callback(ans) {
    // This function will return 
    // another function with the ans 
    // variable set, which in turn 
    // will be called as a callback 
    // when needed by the 'click' event.
    return function () {
        if (q[i][0] === ans) {
            correct++;
        } else {
            incorrect++;
        };

        if (i < q.length - 1) {
            i++;
            document.getElementById('question').innerText = q[i][1];
        } else {
            location.href = "answer.html";
        }
    }
}