關於jQuery出現的新添加元素點擊事件無效

1 $('.chooseAddress-show').on('click',function(){
2                 $(this).next().slideDown('slow');
3                 console.log(1);
4             });

開始我是這樣寫的事件綁定,而後建立新的元素瀏覽器

 1  $('#address-btn').on('click',function(){
 2                 var inLocation = document.getElementById('in-location').value;
 3                 var inName = document.getElementById('in-name').value;
 4                 var inPhone = document.getElementById('in-phone').value;
 5                 var result = '<li>'+
 6                         '<div class="chooseAddress-show">'+
 7                             '<div class="chooseAddress-mouren">'+ '</div>'+
 8                             '<div class="chooseAddress-msg">'+
 9                                 '<p>'+ '<span class="icon icon-location">'+ '</span>'+'<span id="chooseAddress-location">'+inLocation+'</span>'+'</p>'
10                                 +'<p>'+'<span class="icon icon-person">'+'</span>'+'<span class="chooseAddress-username">'+inName+'</span>'+'<span class="chooseAddress-phone">'+inPhone+'</span>'+'</p>'
11                             +'</div>'                            
12                         +'</div>'
13                         +'<div class="chooseAddress-menu">'+
14                             '<ol>'+
15                                 '<li>'+'<a href="">'+"默認地址"+'</a>'+'</li>'+
16                                 '<li>'+'<a href="">'+"修改"+'</a>'+'</li>'+
17                                 '<li>'+'<a href="">'+"刪除"+'</a>'+'</li>'+                                
18                             '</ol>'+
19                         '</div>'+
20                     '</li>';
21                 console.log(result);
22                 $('.chooseAddress-wrap ul').append(result);
23             });

發現點擊沒有效果。app

解決辦法是前邊的綁定點擊事件這樣寫ide

1 $(document).on('click','.chooseAddress-show',function(){
2                 $(this).next().slideDown('slow');            
3             })

這樣點擊效果就出來了。this

順便提下,如何就能夠點擊這個div以外的地方纔能觸發事件,代碼以下:spa

 1 $(document).on('click', function(e) {
 2                 var e = e || window.event; //瀏覽器兼容性   
 3                 var elem = e.target || e.srcElement;  
 4                 while (elem) { //循環判斷至跟節點,防止點擊的是div子元素   
 5                     if (elem.className && elem.className == 'chooseAddress-show') {  
 6                         return;  
 7                     }  
 8                     elem = elem.parentNode;  
 9                 }  
10                 $('.chooseAddress-menu').slideUp();                
11             });
相關文章
相關標籤/搜索