在每个输入 HTML/JS 后添加一个逗号

我已经看过很多与这个问题相关的列表,但它们似乎都不起作用或不完全符合我的要求。


我有一个带有 input 的 HTML 文档type="text"。我正在尝试接受用户的数字,每次输入后,都会出现一个逗号。


前任。


User Enters 1234 -> Display 1,2,3,4

我希望将值保存到背面的数组中,所以同样的例子


array[0] = 1

array[1] = 2

array[2] = 3

array[3] = 4

我的 HTML 文件看起来像这样


<div class="input-group mb-3">

    <input type="text" ng-keyup="format(this)">

</div>

顶级 DIV CLASS 使用 ng-controller


<div class="modal-body" ng-controller="SplitCtrl">

我只是好奇如何调用该控制器来创建一个将我的输入分开的函数。


MM们
浏览 132回答 2
2回答

慕的地6264312

我会做这样的事情:<div ng-controller="SplitCtrl">&nbsp; <div class="input-group mb-3">&nbsp; &nbsp; <input type="text" ng-model="text" ng-keyup="format($event)">&nbsp; </div></div>var app = angular.module('myApp', []);app.controller('SplitCtrl',['$scope' ,function ($scope) {&nbsp; $scope.format = function(e) {&nbsp; &nbsp; if ($scope.text.length > 1) {&nbsp; &nbsp; &nbsp; var text = $scope.text.split('').filter(function(_, i) {&nbsp; &nbsp; &nbsp; &nbsp; return (i % 2) === 0;//filter out previous commas&nbsp; &nbsp; &nbsp; }).join('') + e.key;&nbsp; &nbsp; &nbsp; $scope.text = text.split('').join(',');&nbsp; &nbsp; }&nbsp; }}])

跃然一笑

只要您不需要具有多个字符的数字(例如 10 个),这应该可以。<!doctype html><html><head>&nbsp; <meta charset="UTF-8">&nbsp; <script src="//code.angularjs.org/1.8.0/angular.min.js"></script>&nbsp;&nbsp;</head><body ng-app="myApp"><script>&nbsp; angular.module('myApp', [])&nbsp; &nbsp; .controller('AppController', ['$scope', function($scope) {&nbsp; &nbsp; &nbsp; $scope.change = function() {&nbsp; &nbsp; &nbsp; &nbsp; $scope.numbers = $scope.numbers.replace(/,/g, '').split('').join(',');&nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; }]);</script><div ng-controller="AppController">&nbsp; <input type="text" ng-model="numbers" ng-change="change()" /></div></body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript