请帮我解决这个问题。我研究得更多,但我无法解决问题。 我有代码1:
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<script>
function needloadafterloadpage(){
$form = $('<form method="get" action="" id="form-cmtxxx"></form>');
$form.html('<textarea name="add_comment_text" title="Write a comment..." content="Write a comment..." placeholder="Write a comment..." class="textInput mentionsTextarea uiTextareaAutogrow uiTextareaNoResize UFIAddCommentInput DOMControl_placeholder" id="scriptBox26" />');
$('#wrappercontentpost').html($form);
}
</script>
<body>
<div id="wrappercontentpost"></div>
<script>
$('textarea').on('keydown',function(e){
alert("abc");
});
</script>
<script>
needloadafterloadpage();
</script>
</body>
代码jquery在这种情况下不起作用。我希望在10秒后将形式附加到div。你有办法重装Jquery吗? 非常感谢您的支持
答案 0 :(得分:1)
您需要使用事件委派,因为在执行事件注册脚本时,dom中不存在textarea元素
然后使用setTimeout
在10秒后附加表单
function needloadafterloadpage() {
$form = $('<form method="get" action="" id="form-cmtxxx"></form>');
$form.append('<textarea name="add_comment_text" title="Write a comment..." content="Write a comment..." placeholder="Write a comment..." class="textInput mentionsTextarea uiTextareaAutogrow uiTextareaNoResize UFIAddCommentInput DOMControl_placeholder" id="scriptBox26" />');
$('#wrappercontentpost').append($form);
}
jQuery(function ($) {
$('#wrappercontentpost').on('keydown', 'textarea', function (e) {
console.log("abc");
});
})
setTimeout(needloadafterloadpage, 10000)
演示:Fiddle
答案 1 :(得分:0)
更改代码部分:
<script>
$('textarea').on('keydown',function(e){
alert("abc");
});
</script>
有一个:
<script>
$(function() {
$('textarea').on('keydown',function(e){
alert("abc");
});
});
</script>
说明:您没有使用$(function(){ ... });
答案 2 :(得分:0)
$(document).ready(function() {
var form = '<form method="get" action="" id="form-cmtxxx"><textarea name="add_comment_text" title="Write a comment..." content="Write a comment..." placeholder="Write a comment..." class="textInput mentionsTextarea uiTextareaAutogrow uiTextareaNoResize UFIAddCommentInput DOMControl_placeholder" id="scriptBox26" /></form>';
window.setTimeout(function(){$('#wrappercontentpost').html(form);}, 10000);
});
将根据要求在10秒后显示表单。
答案 3 :(得分:0)
试试这个:
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<script>
function addForm() {
var form = '<form method="get" action="" id="form-cmtxxx"><textarea name="add_comment_text" title="Write a comment..." content="Write a comment..." placeholder="Write a comment..." class="textInput mentionsTextarea uiTextareaAutogrow uiTextareaNoResize UFIAddCommentInput DOMControl_placeholder" id="scriptBox26" /></form>';
$('#wrappercontentpost').html(form);
}
$(document).ready(function() {
setTimeout(function() {
addForm();
},10000);
});
</script>
<body>
<div id="wrappercontentpost"></div>
</body>