简体   繁体   English

如果所有div具有相同的类,如何在jquery click事件中从多个div中选择一个div?

[英]how to select a div from multiple div on jquery click event if all div have same class?

I have a div with a class .display_noti and inside it I have append another div with class .palnotific by jquery.I have fetched data from database and i converted that fetched data into json_encode .I used that json format data and made some information which were append on that div with class .palnotific . 我有一个类为.display_notidiv ,并且在其中append另一个类为.palnotificdiv我从数据库中获取了数据,并将获取的数据转换为json_encode 。我使用了json格式的数据并做了一些信息在该div上append.palnotific类。

my first jquery code which append data inside that div with class .display_noti looks like :- 我的第一个jquery代码将.display_noti数据附加到类.display_noti看起来像:-

  $.getJSON("notification.php",function(data){  
    // you can do checking here
    if ( data.result && data.result.length > 0 ) {
       $(".display_noti").empty(); // Clear out the div  
       $.each(data.result,function(){  
         $(".display_noti").append("<div class='palnotific'>You got a pal requet from <strong>"+this['from_user']+"</strong><br><span class='date'>"+this['notification_date']+"<form method='post'><input type='text' class='palid' value='"+this['pals_id']+"'></form></div>");
       }); 
       done();
    }
    else {
          $(".display_noti").append("<div class='palnotific' style='background-color:white;'>You have no notification to view.</div>");
    } 

Above I first get the json format data and I did some validation and then at last I append that second div with class .palnotific inside that first div with a class .display_noti .I have a form inside that append div which I use to take value from a input for use. 上面我先得到JSON格式的数据,我做了一些验证,然后在最后我追加一条第二分度类.palnotific用类第一个div内.display_noti 。我有我使用取值追加DIV中的表单从输入中使用。

As we know .palnotific is an appended div.I wanted to use some Onclick event function on it so, I used below code :- 我们知道.palnotific是一个附加的div。我想在上面使用一些Onclick事件函数,所以我使用了以下代码:-

   $('body').on('click','.palnotific',function(){
   var x = $(this).closest('.display_noti').find('.palid');
   var pid=x.val();  
  $.ajax({
    url:'notifipro.php',
    type:'post',
    data:"palid="+pid,
    success: function(data){
      if(data==1)
        {
         $(window).load('oldpage.php');
        }
      if(data==2)
         {
            $(window).load('newpage.php');
         } 

  } 
  });

});

Above code takes the input value from that form which was inside that .palnotific div which was appended from jquery at previous.As you know those appended div carry data from database via json_encode .It will take value as much as available in database which mean if there's 2 data in database json_encode will also have 2 data and those append div class which takes data from json_encode will append 2 time that div with a class palnotific .Now my problem is that if i have two div with class palnotifi origin from that append my click function work for first div only and when i click on second div onclick function doesn't work.No matter I have 2 or more then two div if I click any one div first div click function takes action.How can I make work onclick function to those div only which have been clicked? 上面的代码从先前从jquery附加的.palnotific div内的格式中获取输入值。如您所知,这些附加的div通过json_encode从数据库中获取数据。它将取值与数据库中的可用值相同,这意味着数据库中有2个数据json_encode也将有2个数据,那些从json_encode中获取数据的append div类将在div上添加2次具有palnotific类的palnotific 。现在,我的问题是,如果我有两个div, palnotifi源是palnotifi类click函数仅适用于第一个div,并且当我单击第二个div时, onclick函数不起作用。无论我是否有2个或更多,如果我单击任何一个div的第一个div click函数都会起作用,则两个div起作用。如何使onclick起作用仅对那些已单击的div功能?

The easiest way to have jquery react on an element that is dynamically created, is to attach the event to that element itself. 使jquery对动态创建的元素做出反应的最简单方法是将事件附加到该元素本身。 Another way would be using on on a the container div with a subfilter, but since you are already creating the html, you can encapsulate it in $('yourhtml') and attach the click directly to that created element. 另一种方法是on带有子过滤器的容器div上使用,但是由于您已经在创建html,因此可以将其封装在$('yourhtml') ,并将点击直接附加到该创建的元素上。 In combination with appendTo instead of append, you can also chain the append and click: 与appendTo组合使用,而不是附加,也可以链接附加并单击:

//mock data:
var data={result: [
          {from_user: 'A',  notification_date: new Date(), pals_id: 1},
          {from_user: 'B',  notification_date: new Date(), pals_id: 2},
          {from_user: 'C',  notification_date: new Date(), pals_id: 3} 
]};


$.each(data.result,function(){  
        var id = this.pals_id;
         $("<div class='palnotific'>You got a pal request from <strong>"+this['from_user']+"</strong><br><span class='date'>"+this['notification_date']+"<form method='post'><input type='text' class='palid' value='"+ id +"'></form></div>")
         .appendTo(".display_noti")
         .click(function(){
             //attach pre existing function or assign your logic here
            alert('You clicked '  + id);
        })
});

Example fiddle 小提琴的例子

In this example, the id was also stored before hand and reused inside the attached click. 在此示例中,id也是事先存储的,并在附加的点击中重新使用。 If you need to use the raw value, you can use $(this).find('.palid').val() (as done in this fiddle ) 如果您需要使用原始值,则可以使用$(this).find('.palid').val() (就像在小提琴中所做的那样)

From the code you paste, the problem should be this line: 从您粘贴的代码中,问题应该是此行:

var pid=x.val(); 

as you can find in jQuery docs ( http://api.jquery.com/val/ ) 您可以在jQuery文档( http://api.jquery.com/val/ )中找到

.val() Get the current value of the first element in the set of matched elements or set the value of every matched element. .val()获取匹配元素集中第一个元素的当前值,或设置每个匹配元素的值。

You can use a more specific CSS3 Selector in the on() function. 您可以在on()函数中使用更特定的CSS3选择器 I'm not entirely sure this is going to solve your overall problem, but it might lead you in the right direction. 我不确定这是否可以解决您的整体问题,但可能会引导您朝正确的方向发展。

$(".display_noti").on("click", ".palnotific:first", function(event) {
  console.log("You Clicked: ", event.target.id);
});

Here is an example JSFiddle ; 这是一个JSFiddle示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM