繁体   English   中英

按键时无法获得动态添加的textarea值

[英]Unable to get Dynamically added textarea value on keypress

在所有这些过程中一切正常,只是现在我为其他功能重构了代码,现在出现了这个愚蠢的问题,我不知道为什么会这样。

jQuery中的textarea标记

 +'<div class="ckit-container__ft" data-ckit-footer>'
            +'<form action="" class="ckit-composer-form">'
                +'<div class="ckit-composer">'
                    +'<textarea data-ckit-composer-textarea placeholder="Add your reply" autocomplete="off" name="message" class="form-control ckit-composer__textarea"></textarea>'
                +'</div>'
            +'</form>'       
        +'</div>

绑定按键事件

jQuery(function($){
jQuery('body').bind('keypress','[data-ckit-composer-textarea]',function(event)
{
console.log(jQuery('[data-ckit-composer-textarea]').val());//returns empty 
console.log(jQuery(this).val());//returns empty string
});
});

由于HTML标记位于$(function(){..}) ,所以我什至尝试克隆模板并找到相关的属性来替换,但没有运气。

var fullChatView = '<div class="ckit-container__ft" data-ckit-footer>'
                +'<form action="" class="ckit-composer-form">'
                    +'<div class="ckit-composer">'
                        +'<textarea data-ckit-composer-textarea placeholder="Add your reply" autocomplete="off" name="message" class="form-control ckit-composer__textarea"></textarea>'
                    +'</div>'
                +'</form>'       
            +'</div>';

var test = $(fullchatView).clone();//ReferenceError: fullchatView is not defined
var val = test.find('[data-ckit-composer-textarea]').val();
console.log(val);

在你的第一个代码示例,更改.bind().on()并使用keyup事件 ,而不是keypress事件

请尝试以下操作:

jQuery(function($) {
    // Note: The $ parameter passed in to this callback function
    // represents the jQuery object, so you can safely use $ inside
    // this function.
    $('body').on('keyup', '[data-ckit-composer-textarea]', function() {
        console.log($(this).val());
    });
});

当触发keypress事件时 ,尚未更改textarea的值以包括按下的键。

jQuery('body').on('keypress','[data-ckit-composer-textarea]',function(event) { });

文献资料

从jQuery 1.7开始,.on()方法是将事件处理程序附加到文档的首选方法。 对于早期版本,.bind()方法用于将事件处理程序直接附加到元素。

尝试使用jQuery.parseHTML()

在哪里进行克隆

暂无
暂无

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

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