如何在on('click')捕获中获得嵌套值

how to get nested values in an on('click') capture

本文关键字:嵌套 on click      更新时间:2023-09-26

我有以下内容:

  <div class='outer'>
  outside these values
    <div data-which-price="special">
      special price
    </div>  
    <div data-which-price="regular">
      regular price
    </div>  
  </div>  

我想捕获外部的点击,但是如果他们在一个data-which-price中点击,我想捕获它。我不知道该怎么做。我有(bin at http://jsbin.com/capet/3/):

$('body').on('click','.outer', function(){
   var which_price_val=$(this).attr('data-which-price');
   console.log('here i am');
    if(which_price_val){
      console.log('price is: ' + which_price_val);
    }
});

,但这不是做它。我该怎么做呢?

jQuery on方法的第二个参数允许使用逗号分隔的匹配元素列表,因此

$('body').on('click','.outer, [data-which-price]',
第二个元素的

将提供您所需要的

如果你在父div中应用事件,我也会在子div中应用,所以如果你点击外部类或data-which-price相同的函数onClick将被调用。但是如果你想调用单独的函数来调用子click,你必须做以下事情:-

    $(document).ready(function(){
    $('body').on('click','.outer', function(e){
         console.log("clicked outer")
     });
    });
   $(document).ready(function(){
   $('body').on('click','[data-which-price="regular"]', function(e){
   e.stopPropagation();
   console.log("clicked inner")
   });
  });