使用jQuery .each()的动态限制的字符计数器
这个问题是使用类的jQuery字符计数器的扩展? 。
我想在我的textarea字段中添加一个data-content="####"
,然后使用jQuery提取数值并将其应用于字符计数器限制器。
此字段的限制为2000个字符
此字段的限制为1000个字符
这个将是1500个字符。
从我的其他问题的解决方案(参见下面的解决方案),我假设我需要从DOM中提取数据内容然后将其应用于目标。 我只是不知道如何从数据内容中提取价值,并希望得到一些帮助。
$(document).ready(function(){ $(".limitChars").each(function() { $(this).counter({ goal: 500 }); }); });
================================================== ===
通过发生的扩展对话框,我认为显示实际结果可能会有所帮助:
HTML
的JavaScript / jQuery的
$("[data-counter-limit]").each(function() { var $this = $(this), limit = +$(this).data("counter-limit"); $this.counter({ goal: parseInt(limit,10) // goal: limit }); });
使用.data()
方法从data-
属性中提取值。 然后使用parseInt(string, radix)
将其转换为数字
$(document).ready(function(){ $('.limitChars').each(function() { var self = $(this); self.counter({ goal: parseInt(self.data('content'),10) }); }); });
您可以删除classname limit500
并直接使用data-*
属性, data-counter-limit
。 它比使用两者更清洁。
$("[data-counter-limit]").each(function() { var $this = $(this), limit = +$(this).data("counter-limit"); $this.counter({ goal: limit }); });
selector [data-counter-limit]
将获得具有属性data-counter-limit
所有元素。 剩下的就是解析限制并应用处理元素。