简体   繁体   English

为什么这个jQuery事件监听器不起作用?

[英]Why does this jQuery event listener not work?

I'm trying to setup an event listener in jQuery but can't seem to get it to work. 我正在尝试在jQuery中设置一个事件监听器,但似乎无法让它工作。 Any tips/hints as to what I'm doing wrong would be greatly appreciated. 任何关于我做错的提示/提示都将不胜感激。 Here is the code: 这是代码:

<script>
$('.send').on('click', function() {
    console.log('message sent');
    var text = $('.draft').val();
    Chat.send(text); 
});
</script>
<input class="draft" type="text"/> <button class="send">Send</button>

-EDIT- -编辑-

When I say it doesn't work, I mean that the event handler doesn't seem to be running (console doesn't show anything when I hit the send button). 当我说它不起作用时,我的意思是事件处理程序似乎没有运行(当我点击发送按钮时控制台没有显示任何内容)。

In your HTML you have input 在您的HTML中,您有输入

<input class="draft" type="text"/>

and here in jQuery, you are doing wrong text(); 在jQuery中,你做错了text();

 var text = $('.draft').text();

it should be val(); 它应该是val();

 var text = $('.draft').val();

Fiddle 小提琴

Edit: 编辑:

Make your script DOM ready 使您的脚本DOM准备就绪

//jQuery Library Always comes FIRST
<script>
$(document).ready(function() {
    $('.send').on('click', function() {
        console.log('message sent');
        var text = $('.draft').val();
        Chat.send(text); 
    });
});
</script>

<input class="draft" type="text"/>
<button class="send">Send</button>
<input class="draft" type="text"/> <button class="send">Send</button>
<script>
    $('.send').on('click', function() {
        console.log('message sent');
        var text = $('.draft').val();
        console.log(text);
        //Chat.send(text);
    });
</script>

Event handler should be on '.send' button if you are expecting it to console when you click the button. 如果您希望在单击按钮时控制台,则事件处理程序应位于“.send”按钮上。 $('.send').on('click', function(){});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM