尝试将span值传递给函数,但无法从通过输入文本字段接收的范围中获取值。
以下是我的代码:
HTML
<div id="tags" style="border:none">
<span class="tag" id="4"></span>
<input type="text" id="inptags" value="" placeholder="Add 5 main categories (enter ,)" />
</div>
的Javascript
<script type="text/javascript">
$(function () {
$('#tags input').on('focusout', function () {
var txt = this.value.replace(/[^a-zA-Z0-9\+\-\.\#]/g, '');
if (txt) {
$(this).before('<span class="tag">' + txt.toLowerCase() + '</span>');
}
this.value = "";
}).on('keyup', function (e) {
if (/(188|13)/.test(e.which)) $(this).focusout();
if ($('#tags span').length == 5) {
alert('Reached Maximum!');
document.getElementById('inptags').style.display = 'none';
}
});
$('#tags').on('click', '.tag', function () {
$(this).remove();
document.getElementById('inptags').style.display = 'block';
});
});
</script>
使用上面的jquery函数,我可以在输入文本中输入值,并将其存储为span元素。我想传递正在输入的值&#39;输入密钥&#39;或&#39;,&#39; 。我该怎么办?
我尝试在keyup事件中使用$(this).innerHTML,它不起作用。
修改
在密钥启动事件中,我尝试按照下面的答案(trincot)中的建议调用带有span值的方法:
.on('keyup', function (e) {
if (/(188|13)/.test(e.which)) $(this).focusout();
if (/(188|13)/.test(addnewrow(this.value))) $(this).focusout();
});
function addnewrow(inputtext)
{
alert('New row is : '+inputtext);
}
问题在于,只要我输入文本,警报就会得到..只有在按下“输入”后才能获得带有范围值的警报。或&#39;,&#39; ?
答案 0 :(得分:1)
像this.value
处理程序一样使用focusout
:
if (/(188|13)/.test(this.value)) $(this).focusout();
你可能希望改进那个正则表达式。如果您想在用户输入逗号,分号,连字符或空格后立即添加标签:
if (/([,;- ])/.test(this.value)) $(this).focusout();
您可以根据自己的喜好扩展字符列表。
要回复输入键(不会更改值),您可以使用keyCode
上的测试进行扩展:
if (e.keyCode == 13 || /([,;\- ])/.test(this.value)) $(this).focusout();
答案 1 :(得分:1)
您可以使用keydown
事件代替keyup
,如下所示。
$('#tags input').on('focusout', function () {
var txt = this.value.replace(/[^a-zA-Z0-9\+\-\.\#]/g, '');
if (txt) {
$(this).before('<span class="tag">' + txt.toLowerCase() + '</span>');
}
this.value = "";
}).on('keydown', function (e) {
if(e.which==13 || e.which==188){
addnewrow($(this).val());
$(this).val('');
return;
}
});
希望这会对你有所帮助。