我有这段代码:
JS
<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>
HTML
var a = document.getElementById("quantity");
var quantity = a.substring(0,1);
我不能只改变HTML的HTML。如何让它输出第一个字符,所以我实际得到的是一个数字(2,3,4,5或6)。
我尝试了这个,但它打破了剧本:
roDeviceInfo
答案 0 :(得分:4)
你很亲密。您希望将substring()
与 value
一起使用:
var a = document.getElementById("quantity");
a.addEventListener("change", function() {
var quantity = a.value.substring(0, 1);
console.log(quantity);
});
&#13;
<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>
&#13;
答案 1 :(得分:1)
使用正则表达式获取值中的第一个数字时,比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个以上的人。