【问题标题】:Get content of value attribute with javascript and css selectors使用 javascript 和 css 选择器获取 value 属性的内容
【发布时间】:2016-05-10 09:46:45
【问题描述】:

我想用 Javascript 和 CSS 选择器提取这段代码中的 18.99 美元。这可能吗。如果有,怎么做?

<input type="hidden" name="priceBefore" value="$18.99" />

【问题讨论】:

  • 什么代码?可以发一下吗?
  • 所以选择元素并读取输入的值,有什么难的?

标签: javascript css-selectors


【解决方案1】:

您可以将 css 选择器与 Document.querySelector() 一起使用。

文档:https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

window.onload = function() {
  var input = document.querySelector('[name=priceBefore]');

  if (input) {
    document.body.innerHTML += input.value;
  }

};
&lt;input type="hidden" name="priceBefore" value="$18.99" /&gt;

【讨论】:

  • 最好通过名称获取它,而不是使用 document.write 并在 DOM 加载后执行它。
  • @Pamblam。谢谢你的提示。生病改变它
  • querySelector 调用应该在window.onload 中,但为了安全起见,你真的应该把整个东西放在 onload 调用中..
【解决方案2】:

也许:

document.getElementsByName("priceBefore")[0].getAttribute("value");

【讨论】:

  • 不使用 css 选择器
  • 有问题的项目有一个名称集。通过css选择器查​​询似乎有点多余。
  • 谁在乎它的样子,这是个问题。
  • 请注意,这将在值中包含“$” - 如果您想进行计算,则需要将其删除。该值也将是一个字符串,因此需要使用 parseFloat() 将其转换为数字,这将允许小数点和小数位
猜你喜欢
  • 1970-01-01
  • 2012-12-15
  • 1970-01-01
  • 2015-01-04
  • 2013-05-10
  • 2020-01-02
  • 2016-11-30
  • 2013-06-10
  • 2015-09-21
相关资源
最近更新 更多