无法在jquery中获取div元素的click事件

时间:2016-07-25 11:51:57

标签: javascript jquery

这个问题太奇怪了,标题可能似乎没有完全解释其含义,所以这就是我的意思,我有div列表彼此嵌套,我可以获得点击事件和外部Div的其他事件但是无法获得点击事件和内部div的其他事件及其内容。下面是我的代码

    var scrollWidth = 124;
var currentPhoto;
var defaultDisplayPhoto = 5;
var maxScrollCount=0;
var maxScroll =(scrollWidth*currentPhoto)-(scrollWidth*defaultDisplayPhoto);
var maxScroll;
var timeCounter;
var duration = 1000; //time to wait to fire the event;
var photoAllowed = 12;
var canAddMore;

var eventCounter= [];    
            $("input.upload").on('change',function(event){
               $(".mycarousel-container").show();
               if(eventCounter){
                   i=eventCounter.length;
               }else{
                   i=0;
               }
               imgsrc = URL.createObjectURL(event.target.files[0]);
               //for(var i=0; i <eventCounter.length; i++)
var div = $("<div class='mycarousel' style='left:"+left+"px' id='picture"+i+"'></div>");
               var transparentDiv = $("<div class='transparent'></div>");
 var deleteIcon = $("<span class=\"deletebutton\"><i class=\"glyphicon glyphicon-trash\"></i></span>");
               var imgPreview = "<img  class='myimg' src="+imgsrc+">"
               transparentDiv = transparentDiv.html(deleteIcon);
               div = div.html(transparentDiv);
               div = div.append(imgPreview);
               $(".carouser-inner").append(div);

               left = left+120;

               eventCounter.push(imgsrc);
               if(eventCounter.length>5){
                    $("#carousel_control_left").show();
                    $("#carousel_control_left").addClass('myActive');
                    scrollThumb('Go_R');
                }else{
                    $("#carousel_control_left,#carousel_control_right").hide();
                }

                if(eventCounter.length == 12){
                    alert('end')
                    $("input.upload").attr('disabled',true);
                }else{
                    $("input.upload").attr('disabled',false);
                }

           });


      $('.mycarousel').click(function(){
        alert('this is inner div with border color blue');
      });
      $('.myimg').click(function(){
       alert('this is inner image');
      });

DEMO ON FIDDLE 请看小提琴上的演示并添加一些图像和div将显示,现在尝试获取div的点击事件,边框颜色为蓝色或其中的图像

3 个答案:

答案 0 :(得分:2)

使用$(document).on因为当您指定click事件时,div元素不在DOM中

 $(document).on( 'click', '.mycarousel', function () {
        alert("here");
   });

答案 1 :(得分:1)

您无法注册静态侦听器,因为您动态添加项目。您可以使用on代替document

$(document).on("click", '.mycarousel', function(){
    alert('this is inner div with border color blue');
});

$(document).on('click', '.myimg', function() {
    alert('this is inner image');
});

答案 2 :(得分:0)

试试这个。

$(document).on('click', '.mycarousel' , function() {
    //code here ....
});
相关问题