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

实现用户输入1-10数字序列逐行展示(3的倍数标红)

解决方案:处理数字序列并高亮3的倍数

Hey there! Let's tweak your code to hit all your requirements. Right now, your script just dumps the input text directly into the span—we need to split the input into individual numbers, loop through them, spot multiples of 3, and render each entry on a new line with the correct styling.

Here's the updated code that does exactly what you need:

<html>
<head>
<script>
function testVariable() {
    // Grab input value and split into an array of number strings
    var inputText = document.getElementById("textone").value;
    var numbers = inputText.split(/\s+/); // Split on any whitespace (spaces, tabs, line breaks)
    
    var resultContainer = document.getElementById('resultContainer');
    // Clear old results before adding new ones
    resultContainer.innerHTML = '';
    
    // Loop through each entry from the input
    numbers.forEach(function(numStr) {
        var num = parseInt(numStr);
        // Only process valid numbers between 1 and 10
        if (!isNaN(num) && num >= 1 && num <= 10) {
            var lineItem = document.createElement('div');
            lineItem.textContent = num;
            
            // Highlight multiples of 3 in red
            if (num % 3 === 0) {
                lineItem.style.color = 'red';
            }
            
            // Add the formatted line to the result area
            resultContainer.appendChild(lineItem);
        }
    });
}
</script>
</head>
<body>
    <input type="text" id="textone" placeholder="Enter numbers 1-10 (separated by spaces)" />
    <button onclick="testVariable()">Submit</button>
    <br />
    <div id="resultContainer"></div> <!-- Swapped span for div to support block-level line breaks -->
</body>
</html>

Key improvements explained:

  • Input splitting: Uses split(/\s+/) to handle any kind of whitespace separation (spaces, tabs, etc.) so users can enter numbers flexibly
  • Input validation: Checks that each entry is a valid number between 1 and 10, ignoring invalid inputs
  • Line breaks: Creates <div> elements for each number instead of plain text, ensuring each entry shows up on its own line (swapped the original span to a div for proper block layout)
  • Color highlighting: Adds inline red styling to any number divisible by 3
  • Result clearing: Wipes previous results each time the button is clicked, so old entries don't pile up

Give it a test—enter something like 1 2 3 4 5 6 7 8 9 10 and hit submit, and you'll see the multiples of 3 pop up in red!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:37:23