2012-02-03 30 views
0

嘿傢伙我有JS後續代碼:jQuery的事件不工作在JavaScript

$(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我有鏈接,例如:

<a href='#' class="replyLink">Reply</a> 

,當我點擊這個形式切換「某處」,但我不能用html代碼來控制htmlForm()的代碼! TNX

回答

1

不能綁定事件處理程序直接針對尚未存在的元素。可能是解決這個問題的最簡單的變化是在你的文件準備好處理程序創建的所有形式的前面,而不是在「.replyLink」創建它們一次一個單擊處理程序。請注意,當前每次調用click處理程序時,都會通過設置父「#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 */ 
    }); 
}); 

如果由於某種原因,不想要怎麼辦的事我能想到的其他三種方式來解決這個問題適合:

  1. 綁定內的焦點事件你的「 .replyLink「單擊處理程序,然後創建表單元素。

  2. 使用委派事件處理,即,使用.delegate().on()(或者,如果你有一個非常老版本的jQuery .live()),而不是.focus()到事件處理程序附加到確實存在的父元素。這將自動應用於稍後添加的元素。

  3. 不要動態創建表單元素。需要時在您最初的HTML標記和.hide().show()它的形式。

+0

哇謝謝你它的工作:)關於 – 2012-02-03 22:51:00

+0

嗯,你能告訴我如何設置爲attr htmlForm()該特定元素的形式 - [ID]的ID? – 2012-02-05 13:33:33

0

必須經過 $("#form-to-"+this.id).html(htmlForm()).toggle(500);

調用.focus創建窗體 - >然後集中到現場。

1

Fedya Skitsko是正確的,你的形式添加到DOM之前,所以它不會附加該偵聽器被綁定到的項目。

如果您使用的是jQuery 1.7+,我會建議使用「on」事件來綁定焦點事件,以便您可以捕獲在初始化偵聽器綁定後將其添加到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/

+0

這是另一個爲什麼,但它不工作我的問題,我嘗試它,但是,謝謝。問候 – 2012-02-03 22:52:01