【问题标题】:Grab first letter from string从字符串中获取第一个字母
【发布时间】:2018-07-11 01:10:02
【问题描述】:

我有这个代码:

JS

 var a = document.getElementById("quantity");
   var quantity = a.value;

HTML

<select id="quantity" name=''>
  <option title='Option 2' value='2 people'>2 people</option>
  <option title='Option 3' value='3 people'>3 people</option>
  <option title='Option 4' value='4 people'>4 people</option>
  <option title='Option 3' value='5 people'>5 people</option>
  <option title='Option 4' value='6 people'>6 people</option>
</select>

我不能只更改 JS 的 HTML。如何让它输出第一个字符,所以我实际输出的是一个数字(2、3、4、5 或 6)。

我试过了,但它破坏了脚本:

var a = document.getElementById("quantity");
var quantity = a.substring(0,1);

【问题讨论】:

  • 因为你引用了元素!看看quantity在第一局和最后一局的表现如何。
  • @epascarello 我真的不知道那是什么意思:(
  • 为什么不直接将值设为没有字符串 people 的数字呢?似乎这样会更有意义。
  • 问题不在于如何得到第一个字母,你有那部分是正确的。问题应该是如何获取所选项目的值。

标签: javascript


【解决方案1】:

你很亲密。你想用substring() value:

var a = document.getElementById("quantity");
a.addEventListener("change", function() {
  var quantity = a.value.substring(0, 1);
  console.log(quantity);
});
<select id="quantity" name=''>
  <option title='Option 2' value='2 people'>2 people</option>
  <option title='Option 3' value='3 people'>3 people</option>
  <option title='Option 4' value='4 people'>4 people</option>
  <option title='Option 3' value='5 people'>5 people</option>
  <option title='Option 4' value='6 people'>6 people</option>
</select>

【讨论】:

    【解决方案2】:

    j08691's answer 更健壮和可扩展的解决方案是使用正则表达式来获取值中的第一个数字:

    var a = document.getElementById("quantity");
    var pattern = new RegExp(/([0-9]+)\s.*/);
    a.addEventListener("change", function() {
      var quantity = pattern.exec(a.value)[1];
      console.log(quantity)
    });
    

    这将导致 html 更改为允许 10 人以上。

    【讨论】:

      猜你喜欢
      • 2016-06-03
      • 2019-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多