[英]jQuery event doesnt work on html form in javascript
嘿家伙我在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我有鏈接為ex:
<a href='#' class="replyLink">Reply</a>
當我點擊這個表單切換“某處”,但我無法控制htmlForm()上的元素與代碼! TNX
Fedya Skitsko是對的,在將表單添加到DOM之前,監聽器被綁定到項目,因此它不會附加。
如果您正在使用jQuery 1.7+,我建議使用“on”事件來綁定焦點事件,這樣您就可以捕獲在綁定初始偵聽器后將其添加到DOM時對表單所做的事件。
$(document).on('focus', function(){
$(this).css({
'background-color': 'white',
'border':'1px solid #3faefc',
'box-shadow': '0px 0px 2px 1px #95d3ff'
});
});
在1.6之前的版本中,您可以使用.live()或.delegate()
您不能直接將事件處理程序綁定到尚未存在的元素上。 修復此問題的最簡單的更改可能是在文檔就緒處理程序中預先創建所有表單,而不是在“.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 */
});
});
如果由於某種原因不符合您想要做的事情,我可以考慮另外三種方法來解決這個問題:
在創建表單元素后,將焦點事件綁定在“.replyLink”單擊處理程序中。
使用委托事件處理,即使用.delegate()
或.on()
(或.live()
如果你有一個非常舊版本的jQuery)而不是.focus()
將事件處理程序附加到父元素存在。 然后,這將自動應用於稍后添加的元素。
不要動態創建表單元素。 在您最初的HTML標記和形式.hide()
或.show()
需要時。
你必須在$("#form-to-"+this.id).html(htmlForm()).toggle(500);
之后調用.focus
$("#form-to-"+this.id).html(htmlForm()).toggle(500);
創建表單 - >然后專注於字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.