如何仅打印特定的类值

时间:2017-11-16 07:11:30

标签: javascript jquery

我在视图中有3个div。每个div都有唯一的single_value。所以,当我点击任何一个时,它应该警告该数据值。为此,我使用了以下脚本

  $(document).on('click','.single_school',function(){
      var school = $( ".single_school" ).attr('data-value');
        alert(school)
      });

但问题是,我只是获得第一个值,无论我点击什么div。如何仅打印我单击的特定div。

以下是视图:

<div class="col-md-2 col-sm-4 col-xs-12">
    <div class="single_school" data-value="1">
        <div class="selection_area choosen_school">
            <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
        </div>        
        <div class="school_info">
            <p class="school_name">ABC</p>
        </div>
    </div>
</div>
<div class="col-md-2 col-sm-4 col-xs-12">
    <div class="single_school" data-value="2">
        <div class="selection_area choosen_school">
            <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
        </div>        
        <div class="school_info">
            <p class="school_name">XYZ</p>
        </div>
    </div>
</div>
<div class="col-md-2 col-sm-4 col-xs-12">
    <div class="single_school" data-value="3">
        <div class="selection_area choosen_school">
            <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
        </div>        
        <div class="school_info">
            <p class="school_name">PQR</p>
        </div>
    </div>
</div>

2 个答案:

答案 0 :(得分:1)

$(document).on('click','.single_school',function(){
  var school = $(this).attr('data-value');
    alert(school)
  });

答案 1 :(得分:0)

单击元素时,您应该使用JQuery data()来获取值。其次,您应该使用$(this)来获取当前元素值而不是类名。在您的代码中,它总是会给出一个结果,因为您使用的是$( ".single_school" )。这应该替换为$(this)

&#13;
&#13;
$(document).on('click', '.single_school', function() {
  var school = $(this).data('value');
  alert(school)
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-2 col-sm-4 col-xs-12">
  <div class="single_school" data-value="1">
    <div class="selection_area choosen_school">
      <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
    </div>
    <div class="food_info">
      <p class="school_name">ABC</p>
    </div>
  </div>
</div>
<div class="col-md-2 col-sm-4 col-xs-12">
  <div class="single_school" data-value="2">
    <div class="selection_area choosen_school">
      <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
    </div>
    <div class="food_info">
      <p class="school_name">XYZ</p>
    </div>
  </div>
</div>
<div class="col-md-2 col-sm-4 col-xs-12">
  <div class="single_school" data-value="3">
    <div class="selection_area choosen_school">
      <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
    </div>
    <div class="food_info">
      <p class="school_name">PQR</p>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;