2012-06-20 56 views
2

我使用Ajax/Request將元素加載到div容器中。默認情況下我隱藏了一個輸入框。如果用戶點擊該div上的編輯圖標,我想顯示輸入框。這裏是我的代碼:添加文檔中的新元素後,jquery顯示不工作

HTML代碼加載新的元素放入容器之前

<div class='container'> 
     <input type = 'text' onkeydown='saveFn(event,this)' name = 'editemail' class = 'editemail' style='display:none;  height:20px;' /> 
    </div> 

JS代碼

$(".container").click(function(){ 
     console.log($(this).find(".editemail").show()); //Note it works fine If i didn't load any new elements into the div. 
}); 

控制檯日誌輸出。

<input type="text" onkeydown="saveFn(event,this)" name="editemail" class="editemail" style="height: 20px; " value="[email protected]" title="press enter to save"> 

控制檯日誌將元素加載到容器後的輸出。

<input type="text" onkeydown="saveFn(event,this)" name="editemail" class="editemail" style="height: 20px; display: none; " value="[email protected]" title="press enter to save"> 

即使我也嘗試從該元素中刪除「樣式」屬性並添加新的樣式元素,它仍然不起作用。

回答

3

試試這個:

$(document).on('click','.container',function(){ 

http://api.jquery.com/on/

+0

我想和你一樣告知,但隨着的liveQuery作爲插件很簡單答覆是一樣的。我通過Ajax加載內容。 ('click','container',function(){ 'code' $(document).on('click','container',function(){ $(this).find(「。editemail」)。show(); }); 輸出: 方法調用但輸出相同。爲什麼? – kannanrbk

+0

不是''container'',''.container'' - 你需要用'.'來表示它是一個類。 – Blazemonger

+0

抱歉錯字錯誤。 Click事件已經在我的函數中工作,但「$(this).find(」。editemail「)。show()」不起作用。 – kannanrbk

0

問題是th在click()綁定正在ajax請求後消失。在JQuery中,您可以使用.live()函數來實現此功能,但此功能現在已被棄用,並且他們鼓勵您使用.on().delegate()。就我個人而言,我有很多使用.on().delegate()的headecks,而使用插件livequery

$(function(){ 

    $('#elementId').livequery('click',function(){ 
     //do something on click 
    }) 
}); 

欲瞭解更多信息,請訪問: .livequery() .on() .delegate()

1

試試這個來代替:

$('.container').live('click', function(){ 
    /* Your Code Here */ 
}); 
相關問題