我正在为一个小型论坛写一个脚本,如果点击了(添加新主题),我想在其中加载一个表单。到目前为止一切都很好。。问题是…我需要在加载的表单的文本区域上预生成一些脚本,以添加一些HTML编辑器功能。
我的脚本是:
$(document).ready(function(){
$('div#new_topic_div').hide();
$('a.new_topic_li').on("click",function(e){
var parentID = $(this).closest('ul').attr('id');
var form = "<form id=add_new_topic_form action='' method=POST>'n <input type=hidden id=cat_id value='" + parentID + "' /><table class=add_new_topic_form_table border=0>'n <tr><td colspan=2><?=tjcg_add_topic;?></td></tr><tr><td valign=top><?=tjcg_form_post_title;?></td><td valign=top colspan=2 ><input type=text name=new_topic_title id=new_topic_title><td></tr>'n <tr><td valign=top><?=tjcg_form_post_subject;?></td><td colspan=2 valign=top><textarea name=new_topic_text id=new_topic_text class=test rows='5' cols='45'></textarea></td></tr><tr><td class=add_topic_result></td><td width=50px><input type=submit class=submit_btn value='<?=tjcg_form_submit;?>' /></td><td class=form_result></td></tr>'n <table>'n </form>";
e.preventDefault();
var parent= $(this).closest('li');
var checked = $(this).attr('checked_link');
if (checked == 0)
{
parent.find('div#new_topic_div').html(form).show(200);
$(this).attr('checked_link',"1");
}
else{
parent.find('div#new_topic_div').html('').hide(200);
$(this).attr('checked_link',"0");
}
});
});
表单加载到div#new_topic_div
后,我想将以下脚本应用于加载的表单中的文本区域字段
$("textarea").htmlarea();
这可能吗?
此行之后:
parent.find('div#new_topic_div').html(form).show(200);
只需这样做:
parent.find('div#new_topic_div textarea').htmlarea();
您需要将html属性放在引号中,例如
var form = '<form id="add_new_topic_form" method="post" action="...">';
也就是说,您可以要求文档使用jQuery的.on()
侦听动态创建的元素上的事件。然而,这对你想要做的事情来说是不必要的。你可以在将文本区域加载到DOM后,简单地调用你需要的任何js代码。
示例:
parent.find('div#new_topic_div').html(form).show(200, function() {
$.getScript("some_script_for_textareas.js", function() {
// Got script, do stuff with textarea
});
});
或者简单地说:
parent.find('div#new_topic_div').html(form).show(200, function() {
// do stuff with $("#add_new_topic_form");
$("textarea").htmlarea();
});
使用https://api.jquery.com/on/
示例:
$("#container_id/and or class").on("focus", "#new_topic_div", function (e) {
$(this).htmlarea();
});