为什么属性选择器不适用于jQuery?

鞋带1291

我正在尝试data-maxlength使用属性中的任何值获取分配给它们的所有元素然后,每次文本输入或textarea的值更改时,我都希望length在工具提示中显示输入的maxlength以及在Bootstrap工具提示中显示值(x / 250个字符)。

当我输入输入内容时,没有任何反应,没有工具提示,没有错误。甚至我的console.log消息都没有出现在控制台中。此代码有什么问题?

jQuery / JS:

$(document).ready(function(){
    $('[data-maxlength]').find().each(function(){
        console.log('hello');
        $(this).on('keyup', function(){
            console.log('hi!');
            $(this).data('toggle', 'tooltip').data('placement', 'bottom').attr('title', $(this).val().length + ' / ' + $(this).data('maxlength'));
        });
    });
});

HTML:

<textarea class="form-control" rows="7" name="description" data-maxlength="250"></textarea>
i

你不需要用 .find()

$('[data-maxlength]').each(function(){

但是似乎您把它弄错了,应该将事件绑定到选择器本身,该选择器还返回一个集合,并且$(this)将成为您当前的操作元素:

$('[data-maxlength]').on('keyup', function(){
    $(this).data({
       'toggle':'tooltip', 
       'placement' : 'bottom'
    }).attr('title', $(this).val().length + ' / ' + $(this).data('maxlength'));
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章