jquery - 如何在按下逗号键后而不是在按下空格键后获取输入字段内的类型词

标签 jquery html css

我有一个输入字段,我希望输入的单词在按下逗号键后出现一次,而不是在按下空格键后出现一次。目前我是在按下空格键之后。 因此,当我只按逗号键时我该怎么做。

希望你理解我的问题。

HTML

<div id="wrapper">
<input type="text" id="txtNames" placeholder="Type name here"/>
</div>

CSS

.tagsDiv
{
background-color:rgb(165, 215, 175);
color:black;
display: inline-block;
padding:5px;
height:30px;
margin:10px;
border-radius:5px;
}

.innerBody{
display:inline-block;
padding: 5px;
}
.close{
margin-left:-5px;
position:absolute;
margin-top:-7px;
text-decoration: none !important;
}
#wrapper{
width:400px;
min-height:200px;
border:black 2px solid;
}
#txtNames{
border:none;
outline:none;
padding:15px;
}

JS

function createTag(vals)
{
var html='<div class="tagsDiv">'
         +'<div class="innerBody">'+vals.trim()+'</div>'
         +'<a href="#" class="close">x</button></div>';
$(html).insertBefore('#txtNames');
$('#txtNames').val('')
}


$("#txtNames").on('keypress',function(e){
if(e.which===32)
{
    if($(this).val().trim()!=='')
    {
    setTimeout(function(){
        createTag($('#txtNames').val());   
    },0);
    }
}
});

$(document).on('click','.close',function(){
$(this).parents('.tagsDiv').remove();
});

最佳答案

空格键的 keyCode 是 32。逗号的 keyCode 是 188。

替换

if(e.which===32)

if(e.which===188)

在您的 keypress 处理程序中。

更新

对于防止显示逗号以及允许 enter 键的特定需求,请尝试以下操作:

$("#txtNames").on('keydown', function (e) {
    // Grab the textbox value
    var value = $(this).val();

    // Check for ENTER or COMMA
    if (e.which === 13 || e.which === 188) {
        if(value) {
            createTag(value);   
        }

        // Cancel the event, preventing the ',' from 
        // appearing in the input box
        e.preventDefault();
    }
});

关于jquery - 如何在按下逗号键后而不是在按下空格键后获取输入字段内的类型词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30659260/

相关文章:

html - h3 文本已溢出

javascript - 向上滚动时自动显示/隐藏导航更改颜色

html - 我的一些页面在 IE 中看起来乱七八糟

java - 如何使用 Selenium webdriver 找到具有相同 CSS 类的第二个值

java - Spring MVC 上的 AJAX POST 请求返回 404

html - 如何从 ul/li 元素可变高度设置自动 div 高度

javascript - JQuery 循环闪烁图像

javascript - 如何使用 javascript 获取动态加载的 swf 的大小?

jquery - 使用 Jquery 随机设置图像的宽度

jQuery UI - 添加选项卡