给出如下输入:
<input type="test" value="3,4,9" />
Run Code Online (Sandbox Code Playgroud)
删除像9,4或3这样的值的最佳方法是什么,没有逗号问题,我不希望这样结束:
value="3,4,"
value="3,,9"
value=",4,9"
Run Code Online (Sandbox Code Playgroud)
有没有一种干净的方法来完成JavaScript/jQuery?
您可以将值拆分为数组,然后过滤掉您不想要的值.
$("input[type='test']").val().split(",") // ["3","4","9"]
.filter(function(v){return !isNaN(parseInt(v))}) // filter out anything which is not 0 or more
Run Code Online (Sandbox Code Playgroud)
这是一个不太简洁的版本,它过滤掉任何非数字的东西
var array = $("input[type='test']").val().split(",");
// If you are dealing with numeric values then you will want
// to cast the string as a number
var numbers = array.map(function(v){ return parseInt(v)});
// Remove anything which is not a number
var filtered = numbers.filter(function(v){ return !isNaN(v)});
// If you want to rejoin your values
var joined = filtered.join(",");
Run Code Online (Sandbox Code Playgroud)
最后更改输入值
$("input[type='test']").val(joined);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11039 次 |
| 最近记录: |