如何在 javascript 中正确地将绑定切换到 on 或 live
How to properly switch a bind in javascript to on or live?
我是php的新手,我正在尝试通过教程来学习。现在,我正在编写一个聊天教程。最近,我遇到了一个问题,教程要求我使用 bind,但我认为它不再适用于 jquery。我正在尝试将消息扔到我的消息框中。这是我的javascript的代码
var chat = {}
chat.fetchMessages = function () {
$.ajax({
url: 'ajax/chat.php',
type: 'post',
data: { method: 'fetch' },
success: function(data) {
$('.chat .messages').html(data);
}
});
}
chat.throwMessage = function (message) {
if ($.trim(message).length != 0) {
$.ajax({
url: 'ajax/chat.php',
type: 'post',
data: { method: 'throw', messsage: message },
success: function(data) {
chat.fetchMessages();
chat.entry.val('');
}
});
}
}
chat.entry = $('.chat .entry');
chat.entry.bind('keydown', function(e) {
if (e.keyCode === 13 && e.shiftKey === false) {
chat.throwMessage($(this).val());
e.preventDefault();
}
});
chat.interval = setInterval(chat.fetchMessages, 4000);
chat.fetchMessages();
以下是正在发送信息的 php 文件:
<?php
require '../core/init.php';
if (isset($_POST['method']) === true && empty($_POST['method']) === false) {
$chat = new Chat();
$method = trim($_POST['method']);
if ($method === 'fetch') {
$messages = $chat->fetchMessages();
if (empty($messages) === true) {
echo 'There are currently no messages in the chat';
} else {
foreach($messages as $message) {
?>
<div class="message">
<a href="#"><?php echo $message['username']; ?></a> says:
<p><?php echo $message['message']; ?></p>
</div>
<?php
}
}
} else if ($method === 'throw' && isset($_POST['message']) === true) {
$message = trim($_POST['message']);
if (empty($message) === false) {
$chat->throwMessage($_SESSION['user'], $message);
}
}
}
当我打开检查器时,所有测试都正常工作,但 php 代码似乎没有将数据放在我的消息框中。
$(document).on('keydown', chat.entry, function(e) {
if (e.keyCode === 13 && !e.shiftKey) {
e.preventDefault();
chat.throwMessage( this.value );
}
});
而不是document
使用而是使用#element
使用"bind"时,只有现有元素会受到影响,如果您添加另一个元素,则此元素将不受事件的影响。
Live 会影响现有元素和将在运行时添加的元素。
相关文章:
- 将.live或.on添加到jquery函数中
- 如何使用ON而不是LIVE
- jQuery live()已弃用:对mouseenter和mouseout使用on
- 可以是bind()/on()/live(),jQuery的事件的完整列表
- 从jquery live切换到on不起作用
- jquery .on 在 UI 日期选择器中从 .live 转换后不起作用
- 在纯 JS 中重新创建 jQuery live/on
- jQuery on or live?
- 单页应用程序从 .live() 升级到 .on()
- 如何在 javascript 中正确地将绑定切换到 on 或 live
- 将.live()转换为.on()或.click()函数jquery
- jquery 1.11.1 - live vs on
- 正在尝试将$.live(.)替换为$.on(.)
- 如何将 .live() 方法替换为 .on() 方法
- JQuery - 在哪里添加 .on()/.live() 来函数
- jQuery.on(“点击”)-.live()的替代方案
- 用on函数替换live
- Sublime text find并替换为regex,将jquery live()事件转换为on()
- jquery升级中的jquery.live to.on
- JQuery中的on/live事件是如何工作的