我的jQuery包装方法不起作用

时间:2015-07-08 04:00:23

标签: javascript jquery plugins

我试图使用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

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

4 个答案:

答案 0 :(得分:0)

您可以使用以下方式将其换行:

   (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()命令

答案 1 :(得分:0)

不太清楚为什么,但看起来你想要包装尚不存在的元素。除非在e.preventDefault()之后将元素包起来,否则应该这样:

prepend

参见 DEMO

p / s:这只是您问题的另一种解决方案,不知道为什么原始代码也没有。

答案 2 :(得分:0)

只需在追加输入元素后移动包装代码。

DEMO

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

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

答案 3 :(得分:-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