You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Bootstrap Modal中展示JavaScript随机抽奖结果

问题修复:彩票抽奖Modal无法显示中奖号码

问题根源

  • 重复ID冲突:页面存在两个id="test"的元素,document.getElementById()只会选取第一个匹配的元素,导致Modal内的内容无法更新。
  • 随机数只生成一次:随机数在页面加载时就已生成,每次点击按钮都会使用同一个号码,无法实现每次点击重新抽取。
  • 无效的按钮属性:按钮上重复设置了data-target属性,干扰Bootstrap Modal的触发逻辑。

修正后的完整代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
    <title>彩票抽奖</title>
</head>
<body>
    <div class="container">
        <h2>彩票获奖者抽取</h2>

        <button type="button" class="btn btn-info" data-toggle="modal" data-target="#myModal" id="btn1" onclick="myFunction()">
            选择获奖者
        </button>

        <div class="modal" id="myModal">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h4 class="modal-title">中奖号码</h4>
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                    </div>
                    <div class="modal-body">
                        <p id="winner-number"></p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-danger" data-dismiss="modal">关闭</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        const lotteryNumbers = ["12", "34", "45", "67"];

        function myFunction() {
            // 每次点击重新生成随机索引
            const randomIndex = Math.floor(Math.random() * lotteryNumbers.length);
            const winnerNumber = lotteryNumbers[randomIndex];
            // 控制台输出中奖号码
            console.log(winnerNumber);
            // 更新Modal内的中奖号码
            document.getElementById("winner-number").innerHTML = `恭喜中奖号码:${winnerNumber}`;
        }
    </script>
</body>
</html>

关键修改说明

  • 给Modal内的显示元素设置唯一ID(winner-number),避免ID冲突。
  • 将随机数生成逻辑移至myFunction()内部,确保每次点击都重新抽取号码。
  • 移除按钮上重复的data-target属性,只保留触发Modal的data-target="#myModal"。
  • 优化控制台输出和Modal内的显示文本,提升可读性。

内容的提问来源于stack exchange,提问作者user20656583

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 13:20:28