我的 jQuery 包装方法不起作用

My jQuery wrap method doesn't work

我正在尝试使用 jQuery 包装,但它不起作用。

(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

http://jsfiddle.net/noppanit/sryg5fk7/1/

这样使用怎么样?

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

your updated fiddle

您可以使用以下方式包装它:

   (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>');

DEMO

p/s :这只是您问题的替代解决方案,不确定为什么原始代码也不起作用。

只需在追加输入元素后移动换行代码即可。

DEMO

 $theElement.append($input);
 $input.wrap('<li />');

 $theElement.prepend($span);
 $span.text(tagText).wrap('<li class="tag-choice"></li>');