HTML 表单输入中占位符的值不能在函数内部用 JavaScript 更改

The value of the placeholder in HTML form input cannot be changed with JavaScript from inside of a function

问题与研究: 我必须在 JavaScript 函数中自动更改 HTML 表单输入的占位符值。我做了一些研究。给定的代码不适用于我的情况。我找到了解决方法,但我认为必须有更好的解决方案。另外,我想知道为什么 w3school 中给出的代码示例不适用于我的情况。

要求: 仅 HTML 和原版 JavaScript

代码:

<body>
    <h1>Test JS</h1>
    <form id="search">
        <div id="input_id">
            <input type="text" id="id" name="name" required placeholder="Search...">    
        </div>
        
        <button type="submit">Submit</button>
    </form>

    <script>
        document.getElementById("id").placeholder = "This works outside of the function" 
        document.getElementById('search').addEventListener('submit', SearchIt)
        async function SearchIt (event) {
            event.preventDefault()
            var newVal = "123"
            document.getElementById("id").placeholder = newVal //This line does not work inside the function, why?
            //The following line works but I am looking for a better solution (Vanilla JS only).  
            document.getElementById("input_id").innerHTML = "<input type='text' id='id' name='name' required placeholder=" + newVal + ">"
        }
    </script>

</body>

由于 required 属性,浏览器阻止在输入为空时提交表单。但是如果你在表单中输入一些东西来满足有效性,占位符将不再可见,因为输入中有文本。

要么删除 required 属性,要么在设置新占位符时将输入值设置为空字符串,以便查看新占位符。

document.getElementById("id").placeholder = "This works outside of the function"
document.getElementById('search').addEventListener('submit', SearchIt)
async function SearchIt(event) {
  event.preventDefault()
  document.getElementById("id").placeholder = '123';
}
<h1>Test JS</h1>
<form id="search">
  <div id="input_id">
    <input type="text" id="id" name="name" placeholder="Search...">
  </div>

  <button type="submit">Submit</button>
</form>

document.getElementById("id").placeholder = "This works outside of the function"
document.getElementById('search').addEventListener('submit', SearchIt)
async function SearchIt(event) {
  event.preventDefault()
  document.getElementById("id").placeholder = '123';
  document.getElementById("id").value = '';
}
<h1>Test JS</h1>
<form id="search">
  <div id="input_id">
    <input type="text" id="id" name="name" required placeholder="Search...">
  </div>

  <button type="submit">Submit</button>
</form>