每次按钮如何产生随机选项?

问题描述

 $(function () {
            $("#question2").hide();
            const options = [$("#option1"),$("#option2"),$("#option3"),$("#option4")];

           let randomOption =function (){const texts = options
                .map(opt => opt[0].textContent)
                .sort(() => .5 - Math.random());

            $("#option1").text(texts[0]);
            $("#option2").text(texts[1]);
            $("#option3").text(texts[2]);
            $("#option4").text(texts[3]);}



            $("#question1 button").click(function () {
                $("#question1").fadeOut();
                $("#question2").fadeIn();randomOption()
            })
            $("#question2 button").click(function () {
                $("#question2").fadeOut();
                $("#question1").fadeIn();randomOption()
            })

            console.log(randomOption())
           

        })
 <div id="question1">question 1
        <button id=option1>1</button>
        <button id=option2>2</button>
        <button id=option3>3</button>
        <button id=option4>4</button>
    </div>
    <div id="question2">question 2
        <button id=option1>1</button>
        <button id=option2>2</button>
        <button id=option3>3</button>
        <button id=option4>4</button>
    </div>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script>

为什么函数调用不起作用。

当我按下问题2按钮时。

question2选项不是随机的吗?甚至调用randomOption()。

代码有什么问题?

console.log(randomOption())未定义?

解决方法

按钮的元素是通过id在jquery上选择的,并且id应该是唯一,只能被一次调用,在这种情况下,{{ 1}}到$("#option1")仅在$("#option4")中生效一次,因此解决方案是从<div id="question1">更改为id

class
 $(function () {
            $("#question2").hide();
            const options = [$(".option1"),$(".option2"),$(".option3"),$(".option4")];

           let randomOption =function (){const texts = options
                .map(opt => opt[0].textContent)
                .sort(() => .5 - Math.random());

            $(".option1").text(texts[0]);
            $(".option2").text(texts[1]);
            $(".option3").text(texts[2]);
            $(".option4").text(texts[3]);}



            $("#question1 button").click(function () {
                $("#question1").fadeOut();
                $("#question2").fadeIn();randomOption()
            })
            $("#question2 button").click(function () {
                $("#question2").fadeOut();
                $("#question1").fadeIn();randomOption()
            })

            console.log(randomOption())
           

        })