嘿,伙计们,我有下面的js代码:
$(document).ready(function(){
$(".replyLink").click(function(){
$("#form-to-"+this.id).html(htmlForm()).toggle(500);
return false;
});
function htmlForm(){
var html;
html ='<form class="comment-form" id="form-post" action="request.php" method="post">';
html +='<input type="hidden" name="post_id" value="" />';
html +='<input type="hidden" name="reply" value="" />';
html +='<table><tr><td>Name:</td><td>';
html +='<input class="name" type="text" name="name" size="20" maxlength="30"/>';
html += ......
return html;
}
//this is not working!//////////////////////////////////////////
$(".comment-form input,.comment-form textarea").focus(function(){
$(this).css({
'background-color': 'white',
'border':'1px solid #3faefc',
'box-shadow': '0px 0px 2px 1px #95d3ff'
});
});
/////////////////////////////////////////////////////////////
});HTML我有e.x的链接:
<a href='#' class="replyLink">Reply</a>当我单击此按钮时,表单将切换到“某处”,但我不能使用关于代码来控制htmlForm()上的元素!Tnx
发布于 2012-02-03 08:43:33
您不能直接在不存在的元素上绑定事件处理程序。解决这个问题的最简单的更改可能是在文档就绪处理程序中预先创建所有表单,而不是在".replyLink“单击处理程序中一次创建一个表单。请注意,当前每次调用单击处理程序时,它都会通过设置父对象"# form -to-...“来重新创建表单。元素的html,而不管它是否已经存在。
$(document).ready(function(){
// create the forms up front
$('[id^="form-to-"]').html(htmlForm());
$(".replyLink").click(function(){
$("#form-to-"+this.id).toggle(500); // don't set html here, just toggle
return false;
});
function htmlForm(){
/* your existing function body here */
}
$(".comment-form input,.comment-form textarea").focus(function(){
/* your existing CSS setting code here */
});
});如果由于某种原因,这与你想要做的事情不相符,我可以想出另外三种方法来解决这个问题:
.delegate()或.on() (如果使用的是非常旧的jQuery版本,则使用.live() )而不是.focus()将事件处理程序附加到确实存在的父元素。这将自动应用于以后添加的元素。.hide()或.show()。发布于 2012-02-03 08:42:31
Fedya Skitsko是对的,在您将表单添加到DOM之前,侦听器将被绑定到项,这样它就不会被附加。
如果您使用的是jQuery 1.7+,我建议您使用"on“事件绑定focus事件,以便在绑定初始侦听器之后将表单添加到DOM时捕获对表单所做的事件。
请参阅http://api.jquery.com/on/
$(document).on('focus', function(){
$(this).css({
'background-color': 'white',
'border':'1px solid #3faefc',
'box-shadow': '0px 0px 2px 1px #95d3ff'
});
}); 在1.6之前的版本中,您可以使用.live()或.delegate()
http://api.jquery.com/delegate/
http://api.jquery.com/live/
发布于 2012-02-03 08:22:15
必须在$("#form-to-"+this.id).html(htmlForm()).toggle(500);之后调用.focus
创建表单->,然后聚焦到字段。
https://stackoverflow.com/questions/9121994
复制相似问题