【问题标题】:How to validate a html tag which has contenteditable=true?如何验证具有 contenteditable=true 的 html 标签?
【发布时间】:2017-05-10 12:23:14
【问题描述】:

例如,在输入标签中,我们有一个名为 type 的字段,如果我们将 type ="numeric" 放在其中,则它不允许输入除数字以外的任何内容。

如果我使 td 内容可编辑,我怎么能阻止用户在该 td 标记中输入除数字之外的任何内容。

【问题讨论】:

标签: javascript html angular


【解决方案1】:

您可以尝试在 jQuery 中使用 .keydown() 方法。更干净简洁。见下面的sn-p

$("td").on( "keydown",function(event) {
       if( isNaN(String.fromCharCode(event.which))){
           event.preventDefault(); 
       }
})
td {
	padding:3px;
	border:1px solid red;
	font-size:18px;
	line-height:24px;
	width:100px;
	height:50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
	<td contenteditable="true"></td>
</tr>
</table>

另外,如果您想允许 backspacedel 键(可能有用),请将代码更改为

$("td").on( "keydown",function(event) {
       if(event.which != 8 && event.which !=46 && isNaN(String.fromCharCode(event.which))){
           event.preventDefault(); 
       }
})
td {
	padding:3px;
	border:1px solid red;
	font-size:18px;
	line-height:24px;
	width:100px;
	height:50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
	<td contenteditable="true"></td>
</tr>
</table>

【讨论】:

  • 非常感谢您的快速回答,但我想知道这样的解决方法是否存在?
  • 对于角度来说,你可能想检查汤姆给你的答案:)
【解决方案2】:

您已在此处包含 angular 标签。

angular directive 可能是这样的:

src/onlyNumeric.directive.ts

import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({ selector: '[onlyNumeric]' })
export class OnlyNumericDirective {

    @HostListener('input') onContentChange() {
      this.el.nativeElement.innerText = this.el.nativeElement.innerText.replace(/\D/g,'')
    }

    constructor(private el: ElementRef) {
    }
}

Plunker example here

【讨论】:

    【解决方案3】:

    试试这个

    $('#text').keypress(function(e) {
      if (!(e.which >= 48 && e.which <= 57)) {
        return false;
      }
    });
    

    $('#text').keypress(function(e) {
      if (!(e.which >= 48 && e.which <= 57)) {
        return false;
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table>
      <tr>
        <td>Name
          <td>
            <p contenteditable="true" id="text">000</p>
          </td>
      </tr>
    
    </table>

    【讨论】:

    • 我会用 html5 模式属性替换 onkeypress
    • 非常感谢您的努力,但您能否提供一个不使用输入标签的解决方案,因为输入标签使它看起来。像一个文本框,我不想要那个
    • @geethu jose 这似乎与 jquery 一起工作得很好,但是这个确切的功能在 angular 中的类比是什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-11
    • 2019-05-26
    • 2013-03-14
    • 1970-01-01
    • 2011-05-26
    • 2021-10-09
    • 2013-03-17
    相关资源
    最近更新 更多