javascript - 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>
解决方案
您可以使用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">
推荐阅读
- c# - Assets/line_genertaor.cs(9,5):错误 CS0246:找不到类型或命名空间名称“Line”。您是否缺少程序集参考?
- string-formatting - QString::number 如果数字为正,则用零填充
- c - 仅解析给定参数中的数字
- android - 番石榴依赖错误
- python - 过滤多级分组结果
- angular - HttpTestingController expectOne 匹配 URL 错误
- python - WTForms/flaskforms 无法通过提交按钮正确检索数据
- ios - 在 UICollectionView 中向 AVPlayerViewController 添加图像
- r - 从拟合的 lm 或 glm [R] 获取每个因子水平(以及交互作用)中的数据数量
- dynamics-crm - 当 MS 动态返回 HTTP/1.1 500 内部服务器错误时如何检索 http 响应正文?