jQuery动态事件处理程序错误

时间:2015-01-23 23:17:28

标签: javascript jquery event-handling extension-methods jquery-events

我为动态创建的DOM元素创建了一个事件处理程序,但是收到错误。我做了一个JSFiddle demo,但这里没有发生错误,仅在我的应用程序中。

我添加了两个事件处理程序changeclickchange是我唯一关心的:我只包含click以确保动态DOM元素上的事件处理程序能够正常工作。

如果您不想查看演示,请参阅以下基本代码(我使用的是使用.counter()方法的Word和字符计数器插件,您可以在http://qwertypants.github.io/jQuery-Word-and-Character-Counter-Plugin/):

<!doctype html>
<html>
<head>
    <script>//plugin</script>
    <script>
        $(document).ready(function() {
            $("#myTextArea").counter();
            //Below, my selector is called myTextArea_count because the plugin creates a <span> with an id
            //equal to the id of the element it is counting for, with "_count" appended.
            $(document).on("change", "#myTextArea_count", function() {
                $("<p>Count changed</p>").appendTo("#myTextArea_counter");
            });
            $(document).on("click", "#myTextArea_count", function () {
                var $this = $(this);
                if ($this.css("color") == "rgb(0, 0, 0)") {
                    $this.css("color", "orange");
                }
                else {
                    $this.css("color", "black");
                }
            });
        });
    </script>
</head>
<body>
    <textarea id="myTextArea" rows="4" cols="50"></textarea>
</body>
</html>

这是我在Chrome中长期重复出错的screenshot

这里是踢球者......

我的应用程序中.on("click")事件对我来说正常,而我.on("change")扩展程序中手动触发的$.text()则没有,即使它在JSFiddle中有效。

有谁知道为什么会发生这个错误?

感谢阅读。

1 个答案:

答案 0 :(得分:0)

JSFiddle演示

http://jsfiddle.net/nadeemmnn2007/akkvbu0u/4/

工作样本

<!doctype html>
<html>
<head>


</head>
<body>
    <textarea id="myTextArea" rows="4" cols="50"></textarea>


    <script type="text/JavaScript" src="jquery.js"></script>
    <script src="word-and-character-counter.js"></script>
    <script>
        $(document).ready(function() {

            $("#myTextArea").counter({ count: 'up',
    goal: 10});
            //Below, my selector is called myTextArea_count because the plugin creates a <span> with an id
            //equal to the id of the element it is counting for, with "_count" appended.
            $(document).on("change", "#myTextArea_count", function() {
                $("<p>Count changed</p>").appendTo("#myTextArea_counter");
            });
            $(document).on("click", "#myTextArea_count", function () {
                var $this = $(this);
                if ($this.css("color") == "rgb(0, 0, 0)") {
                    $this.css("color", "orange");
                }
                else {
                    $this.css("color", "black");
                }
            });
        });
    </script>



</body>
</html>

注意:我使用的是https://raw.githubusercontent.com/qwertypants/jQuery-Word-and-Character-Counter-Plugin/master/word-and-character-counter.js插件,而不是缩小版本,Chrome控制台也没有错误