如何通过单击切换特定的 JavaScript 功能?

How to toggle a specific JavaScript function with a click?

我们需要通过单击来禁用和重新启用,该功能会向我们显示大量 < pre > 内的字符数量。

我们使用的函数是这样的:

<script type="text/javascript">
$(window).load(function(){
    $(document).ready(function(){
    $('pre').each(function(i){
        var iCharacters = $(this).text().length;
            $(this).prepend("<b style='color:red'>" + iCharacters + " </b>");
        });
    });
});
</script>

非常感谢您的提前帮助。

我相信一个简单的方法是始终显示数字,但它们会在使用 jQuery 的切换方法单击按钮时隐藏或显示。您可以在这里找到一个工作示例:https://jsbin.com/pohagaz/1/edit?html,js,output.

$("pre").each(function(i){
  var iCharacters = $(this).text().length;
  $(this).prepend("<b class='charCount' style='color:red'>" + iCharacters + " </b>");
});

$("#showCounts").click(function() {
  $(".charCount").toggle();
});