【发布时间】:2017-05-08 22:21:24
【问题描述】:
我想为产品页面上的自定义字段创建字符计数器。我正在尝试使用以下 JavaScript 和 HTML 代码来实现这样的功能:
HTML:
<div class="fields-group-1">
<table class="fields_table product-custom-text-wrapper" cellspacing="0">
<tbody>
<tr>
<td class="label"><label class=" product-custom-text-label" for="custom_text">Custom Text</label></td>
<td class="value">
<input type="text" class="field product-custom-text" name="custom_text" value="" placeholder="Enter Custom Text ..." maxlength="16" type="text" pattern="mandatory" mandatory="no" />
<span class="validation-message is-valid-1"></span>
</td>
</tr>
</tbody>
</table>
</div>
<span id="character_count"></span> //This is where I am attempting to output the Character Count.
JavaScript:
<script type="text/javascript">
$('.product-custom-text').keyup(updateCount);
$('.product-custom-text').keydown(updateCount);
function updateCount() {
var cs = $(this).val().length;
$('#character_count').text(cs);
}
</script>
在 Fiddle 程序中运行它时,我可以生成字符计数器。但是,当我将上述代码放入网站时,字符计数器似乎不起作用。我检查了源代码,所有的编码都在那里。
根据Code works in fiddle, but not on webpage 的问题,我可以看到其他人遇到了与我类似的问题。作为 JavaScript 的新手,我不能 100% 确定合适的修复方法。
是否有人能够指出我需要进行的相关更改才能使上述编码正常工作的正确方向?
【问题讨论】:
-
能否请您发布一个指向您的小提琴的链接。
-
您是否将 jQuery 导入您的页面?还可以尝试将前两行包装在
$(document).ready(function(){}) -
用
$(document).ready(function() { })包装你的JavaScript -
您也在使用 jquery。 JSFIddle 天生就有。但是,当您将脚本包含在 html 中时,您还必须将 jquery 添加到脚本标签并将代码包装在
$(document).ready(function(){})
标签: javascript jquery html