请帮我解决这个问题。我研究更多,但我无法解决问题。我有代码 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。非常感谢您的支持
您需要使用事件委派,因为在执行事件注册脚本时,dom 中不存在 textarea 元素
然后在 10 秒后使用 setTimeout
追加表单
所以总体上
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)
演示:小提琴
$(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 秒后显示。
试试这个:
<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>
演示:http://jsfiddle.net/WrBrx/
更改代码部分:
<script>
$('textarea').on('keydown',function(e){
alert("abc");
});
</script>
用一个:
<script>
$(function() {
$('textarea').on('keydown',function(e){
alert("abc");
});
});
</script>
说明:您没有使用 $(function(){ ... });
初始化 jquery 库