Javascript 为什么属性选择器不能与jQuery一起使用?
我正在尝试获取所有元素,这些元素都使用属性中的任何值为其分配了Javascript 为什么属性选择器不能与jQuery一起使用?,javascript,jquery,Javascript,Jquery,我正在尝试获取所有元素,这些元素都使用属性中的任何值为其分配了data maxlength。然后,每次文本输入或文本区域的值发生变化时,我都希望在工具提示中显示输入的长度,以及引导工具提示中的maxlength值(x/250个字符) 当我输入时,没有任何事情发生,没有工具提示,没有错误。甚至我的console.log消息也不会出现在控制台中。这个代码有什么问题 jQuery/JS: $(document).ready(function(){ $('[data-maxlength]').f
data maxlength
。然后,每次文本输入或文本区域的值发生变化时,我都希望在工具提示中显示输入的长度
,以及引导工具提示中的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()
但似乎您弄错了,您应该将事件绑定到选择器本身,该选择器本身也会返回一个集合,$(this)
将是您当前的活动元素:
$('[data-maxlength]').on('keyup', function(){
$(this).data({
'toggle':'tooltip',
'placement' : 'bottom'
}).attr('title', $(this).val().length + ' / ' + $(this).data('maxlength'));
});
如果没有选择器,则无法使用jQuery方法。您应该向其添加选择器
。查找(选择器)
,或将其删除:
$('[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'));
});
});
希望这有帮助。您正在尝试选择具有
数据最大长度值的元素。您可以使用以下命令。你可以用这里代替
尝试使用属性中的任何值获取已为其指定数据maxlength的所有元素
你可以通过下面的代码找到它
$(document).ready(function(){
alert($(".devTxt").attr("data-maxlength"));
});
$('[data-maxlength]').filter(function(){
$(this).data('maxlength') != '';
}).each(function(){});
$(document).ready(function(){
alert($(".devTxt").attr("data-maxlength"));
});