addEventListener 在尝试使用提示时在页面加载时触发

addEventListener fires on page load when trying to use prompt

我无法让 addEventListener 仅在单击时触发,而不是在页面加载时触发。

我尝试为提示寻找 addEventListener 的答案,但只找到警报的答案并尝试了它们,但没有任何效果。

const poll = {
        question: 'What is your favorite programming language?',
        options: [ '0: JavaScript', '1: PHP', '2: Rust', '3: C++' ],
        registerNewAnswer:
            Number( prompt( 'What is your favourite programming language?\n' +
                '     0: JavaScript\n' +
                '     1: PHP\n' +
                '     2: Rust\n' +
                '     3: C++' ) ),
        answerPoll() {
            switch ( this.registerNewAnswer ) {
                case 0:
                    this.answers[ 0 ]++;
                    console.log( this.answers, 'Vote for JavaScript' );
                    break;

                case 1:
                    this.answers[ 1 ]++;
                    console.log( this.answers, 'Vote for PHP' );
                    break;

                case 2:
                    this.answers[ 2 ]++;
                    console.log( this.answers, 'Vote for Rust' );
                    break;
                case 3:
                    this.answers[ 3 ]++;
                    console.log( this.answers, 'Vote for C++' );
                    break;
                default:
                    console.log( 'Not a Choice on the List Try Again!' );
            }

        },
        answers: new Array( 4 ).fill( 0 )
    };
   

    document.querySelector( '.poll' ).addEventListener( 'click',
        poll.answerPoll.bind( poll ) );

您的 registerNewAnswer 是 属性,它会尝试通过提示您最喜欢的编程语言来计算 属性。如果您的目标是仅在调用 answerPoll() 时才出现该提示,则 registerNewAnswer 需要是 answerPoll().

调用的方法
const poll = {
        question: 'What is your favorite programming language?',
        options: [ '0: JavaScript', '1: PHP', '2: Rust', '3: C++' ],

        registerNewAnswer() { /* <—- you made this a property instead of a method */

            return Number( prompt( 'What is your favourite programming language?\n' +
                '     0: JavaScript\n' +
                '     1: PHP\n' +
                '     2: Rust\n' +
                '     3: C++' ) )
        },
        answerPoll() {

            switch ( this.registerNewAnswer() /* <—- you weren't calling the registerNewAnswer method */  ) {

                // ...
            }
        },
        answers: new Array( 4 ).fill( 0 )
    };