[英]My jQuery wrap method doesn't work
我正在尝试使用jQuery wrap,但是它不起作用。
(function ($) {
$.fn.taggify = function () {
create(this);
return this;
};
function create($theElement) {
var $input = $('<input></input>')
.attr('type', 'text')
.attr('autocomplete', 'off')
.css('border', 'none')
.css('outline', 'none')
.wrap('<li></li>');
$input.on('keyup', function (e) {
if (e.keyCode === 13) {
var tagText = $input.val();
var $span = $('<span class="tag-label"></span>');
$span.text(tagText).wrap('<li class="tag-choice"></li>');
$theElement.prepend($span);
}
});
$theElement.append($input);
}
})(jQuery);
结果仍然没有在输入周围包裹<li>
标记
这是jsfiddle
您可以使用以下方法包装它:
(function ($) {
$.fn.taggify = function () {
var $input = $('<input />')
.addClass('specialInput')
.attr('type', 'text')
.attr('autocomplete', 'off')
.css('border', 'none')
.css('outline', 'none')
.wrap('<li />');
$(this).append($input);
return this;
};
})(jQuery);
$('body').on('keyup','.specialInput',function (e) {
if (e.keyCode === 13) {
$('<li class="tag-choice"><span class="tag-label">'+$(this).val()+'</span></li>').prependTo($(this).parent());
}
});
查看控制台,该错误围绕尝试在非DOM元素上使用.on()
命令的情况
不太清楚为什么,但是看起来您想包装尚不存在的元素。 除非在prepend
之后包装元素,否则它应该像这样工作:
$theElement.append($input);
$input.wrap('<li></li>');
$theElement.prepend($span);
$span.text(tagText).wrap('<li class="tag-choice"></li>');
见演示
p / s:这只是您问题的替代解决方案,不确定为什么原始代码也不起作用。
只需在追加输入元素后移动包装代码即可。
$theElement.append($input);
$input.wrap('<li />');
$theElement.prepend($span);
$span.text(tagText).wrap('<li class="tag-choice"></li>');
这样使用怎么样?
var $input = $('<li><input></input></li>')//wrap li here
.find('input')//find input and use as you want
.attr('type', 'text')
.attr('autocomplete', 'off')
.css('border', 'none')
.css('outline', 'none');
我还注意到您正在使用on方法,但是由于该元素是动态创建的,因此无法使用。 因此,请替换此行:
$input.on('keyup', function (e) {
有了这个:
$(document).on('keyup', $input, function (e) {
//you may use closest parent element instead of document
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.