首页 > 解决方案 > JavaScript 通过 jsname 获取 Input 中的元素值

问题描述

我正在尝试从 html 文件中抓取数据。具体来说,我需要输入中变量的值。下面我有一个输入示例以及到目前为止我尝试做的事情(我特别想获得“数据初始值:

输入:

<input type="username" class="whsOnd zHQkBf" jsname="YPqjbf" autocomplete="current-username" spellcheck="false" tabindex="0" aria-label="Enter your username" name="usernamefield" autocapitalize="off" dir="ltr" data-initial-dir="ltr" data-initial-value="trying to get this" badinput="false">

我的代码:

<script>
    String uname = document.getElementById('usernamefield').value
</script>

标签: javascripthtml

解决方案


您可以使用getAttribute

注意: document.getElementById('usernamefield')选择输入元素,但该输入元素id上有属性。id使用任何其他方式添加或选择。

const input = document.querySelector('input')
console.log(input.getAttribute('data-initial-value'))
<input type="username" class="whsOnd zHQkBf" jsname="YPqjbf" autocomplete="current-username" spellcheck="false" tabindex="0" aria-label="Enter your username" name="usernamefield" autocapitalize="off" dir="ltr" data-initial-dir="ltr" data-initial-value="trying to get this" badinput="false">

由于您需要的属性带有前缀,data因此您可以使用dataset. 请注意,当您将使用dataset属性名称时,将转换为 camelCase。例如initial-value将转换为initalValue

const input = document.querySelector('input')
console.log(input.dataset.initialValue)
<input type="username" class="whsOnd zHQkBf" jsname="YPqjbf" autocomplete="current-username" spellcheck="false" tabindex="0" aria-label="Enter your username" name="usernamefield" autocapitalize="off" dir="ltr" data-initial-dir="ltr" data-initial-value="trying to get this" badinput="false">


推荐阅读