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

Why is the attribute selector not working with jQuery?

本文关键字:适用于 jQuery 不适用 选择器 属性 为什么      更新时间:2023-09-30

我正在尝试使用属性中的任何值获取已分配data-maxlength的所有元素。然后,每次文本输入或文本区域的值更改时,我都希望在工具提示中显示输入的length以及引导工具提示中的maxlength值(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>

您不需要使用.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'));
});

如果没有选择器,就不能使用jQuery方法.find(),您应该向其添加选择器.find(selector)或完全删除它:

$('[data-maxlength]').find(selector).each(function(){
//OR
$('[data-maxlength]').each(function(){

注意:您不应该在each()方法中定义事件,当您跟踪输入更改时,最好使用input事件而不是keyup

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

希望这能有所帮助。

您正在尝试选择具有data-maxlength值的元素。您可以使用以下内容。您可以在此处使用filter()而不是find()

尝试获取所有具有数据最大长度的元素,这些元素具有属性中的任何值

$('[data-maxlength]').filter(function(){
    $(this).data('maxlength') != '';
}).each(function(){});

您可以通过以下代码找到它

$(document).ready(function(){
  alert($(".devTxt").attr("data-maxlength"));
});

https://jsfiddle.net/4eekb7jz/