首页 > 解决方案 > onkeypress() 未调用函数

问题描述

我的任务是不让用户在 textArea 中键入“%”,因此我这样做了

但是,一旦我在文本区域内单击,我仍然可以输入 '%'... 这意味着onkeypress无法识别我的功能,或者功能本身是错误的。

$scope.test = function() {
  var txtarea = document.getElementById("exampleFormControlTextarea1");
  txtarea.addEventListener("input", function() {
    txtarea.value = txtarea.value.replaceAll("%", "");
  })
}

我也尝试过这种方式:

function myfunction () {
        var txtarea = document.getElementById("exampleFormControlTextarea1");
        txtarea.addEventListener("input", function() {
            txtarea.value = txtarea.value.replaceAll("%", "");
        })
    }
<div class="col-md-12 label-base">

  <label for="exampleFormControlTextarea1">Justify</label>
  <textarea style="resize: none" ng-disabled="negociacaoEspecCtrl.proposta.flagDesabilitaEdicaoProposta" 
  class="form-control observacoes" id="exampleFormControlTextarea1" rows="3" 
  ng-model="negociacaoEspecCtrl.proposta.dadosCadastro.negociacaoEspecial.justificativaNegociacaoEspecial"
    onkeypress="test()"></textarea>
</div>

标签: javascriptangularjsfunctioncontrollertextarea

解决方案


从这篇文章:https ://stackoverflow.com/a/35777284/1772933

将过滤器与 ng-change 函数一起使用,例如:

angular.module("test", [])
    .filter("purger", function() {
        return function(input) {
            return input.replace(/%/gi, "");
        }
    }).controller("testController", function($scope, purgerFilter) {
        $scope.onChange = function() {
            $scope.negociacaoEspecCtrl.proposta.dadosCadastro.negociacaoEspecial.justificativaNegociacaoEspecial = purgerFilter($scope.negociacaoEspecCtrl.proposta.dadosCadastro.negociacaoEspecial.justificativaNegociacaoEspecial);
        }
    })

和你的元素:

<textarea ... 
ng-model="negociacaoEspecCtrl.proposta.dadosCadastro.negociacaoEspecial.justificativaNegociacaoEspecial"
ng-change="onChange()"></textarea>

推荐阅读