我有一个 php 聊天页面,其中有群聊和一对一聊天。我正在使用 jquery on change 事件从 php 文件上传函数中获取数据,并将图像 HTML 文本输入到一个 contenteditable div 中,这样也可以和文本。
这在群聊窗口中工作正常,但在单人聊天窗口中却不行。两个聊天窗口代码都在同一个 html 中,带有隐藏显示的 js 样式 block 。无论我做什么,除了 on change 之外的所有东西都不起作用。
我知道在我的代码片段中我仍然需要处理目标,因为它是动态的,但是一旦 on change 事件实际触发,这应该足够简单。
这是表单位,它是在 js/php 函数中构建的,这是唯一一个不起作用 ''''''''''''''''''''''''
modal_content += '<form id="uploadImagesc" method="post" action="php_includes/chat-img-upload-sc.php">';
modal_content += '<label for="uploadFilesc"><i class="fas fa-cloud-upload-alt"></i></label>';
modal_content += '<input type="file" name="uploadFilesc" id="uploadFilesc" accept=".jpg, .png" /></form>';
'''''''''''''''''''''''''''''''''''''
这是群聊中有效的例子 '''''''''''''''''''''''''''''''''''''
<form id="uploadImage" method="post" action="php_includes/chat-img-upload.php">
<label for="uploadFile"><i class="fas fa-cloud-upload-alt"></i></label>
<input type="file" name="uploadFile" id="uploadFile" accept=".jpg, .png" />
</form>
'''''''''''''''''''''''''''''''''''''' 这些是上。更改 JQuery 的位
''''''''''''''''''''''''''''''''''''''''''''' 工作代码
$('#uploadFile').on('change', function(){
'$'('#uploadImage').ajaxSubmit({
target: "#group_chat_message",
resetForm: true
});
});
'''''''''''''''''''''''
无效代码
$('#uploadFilesc').on('change', function(){
// var to_user_id = $(this).attr('id');
// var chat_message = '#chat_message_'+to_user_id;
$('#uploadImagesc').ajaxSubmit({
target: chat_message,
resetForm: true
});
});
所以在这一点上,它只是让 on change 运行第二个函数调用以从 Php 获取数据,我很高兴此刻 onchange 的警报。
最佳答案
它不起作用,因为听起来您正在动态添加 HTML,然后尝试将事件处理程序附加到它。在这种情况下,您需要使用事件委托(delegate),它只是将事件处理程序附加到祖先。
这应该是您需要更改的全部内容:
$(document).on('change', '#uploadFilesc', function() {
// var to_user_id = $(this).attr('id');
// var chat_message = '#chat_message_'+to_user_id;
$('#uploadImagesc').ajaxSubmit({
target: chat_message,
resetForm: true
});
});
将 document
替换为最接近 #uploadFilesc
和 #uploadImagesc
的静态祖先。
关于javascript - JQuery on change 以一种形式而不是另一种形式工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58177228/