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 });
发现点击没有效果。
解决办法是前边的绑定点击事件这样写
1 $(document).on('click','.chooseAddress-show',function(){ 2 $(this).next().slideDown('slow'); 3 })
这样点击效果就出来了。
顺便提下,如何就可以点击这个div之外的地方才能触发事件,代码如下:
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 });