jQuery在输入元素之后添加内容并删除添加的内容 [英] jQuery add content after input element and remove added content

查看:126
本文介绍了jQuery在输入元素之后添加内容并删除添加的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果用户插入非数字格式,我想在文本框后添加<em>标签.

I want to add <em> tag after textbox, if user inserted non-numeric format.

$('.numeric').keypress(function (e) {
 var key_code = e.which;
 if (key_code != 8 && key_code != 0 && (key_code < 48 || key_code > 57)) {
    $(this).after("<em>type only numeric formatted text<em>");
    return false ;
 }
 else {
    $('em').remove();
 }
});

文本框不只一个. HTML代码:

Textboxes more than one. HTML code:

<div>
    <label for="Area">Full Area:</label>
    <input type="text" value="" name="FullArea" id="FullArea" class="numeric">
</div>

在我的jQuery代码中有一些问题:

In my jQuery code have some issues:

  1. 将以非数字格式添加<em>一次以上;

如果用户键入数字格式(也会在其他文本框附近,则页面中的所有em),也会删除所有<em>标记

Will remove all <em> tag, if user typed numeric format (near other textboxes too, all em in page)

需要一种智能的方式来实现此功能,而不会出现问题[1]和[2]. 谢谢.

Need smart way to do this functionality, without issues [1] and [2]. Thanks.

推荐答案

我建议隐藏并显示出来,...比删除并再次添加要便宜得多...

I would suggest to just hide and show that,... it's much cheaper than removing and adding again...

尝试此演示

var em = $("<em>type only numeric formatted text<em>").hide();
$('.numeric').keypress(function (e) {
    var key_code = e.which;
    if (key_code != 8 && key_code != 0 && (key_code < 48 || key_code > 57)) {
       $(this).next("em").show();
       return false ;
    }
    else {
       $(this).next("em").hide();
    }
}).after(em);

这篇关于jQuery在输入元素之后添加内容并删除添加的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆