简体   繁体   English

如何在jQuery中获取可选的div值或ID?

[英]How to get selectable div value or id in jquery?

I was trying to get selected div value or id using jquery selectable .My problem is i have div inside for loops so when im trying to get value or id it is giving me only first div value or id.Below is my code. 我正在尝试使用jquery selectable获取选定的div值或id。我的问题是我在for循环中有div,所以当我尝试获取值或id时,它只给我第一个div值或id。以下是我的代码。

<input type="text" id="mod">
    <div class="row">
      <?php for($i=0;$i<4;$i++){ ?> 
      <div class="col-lg-3 col-md-3 col-sm-6 col-xs-12 list"   >
        <div class="dashboard-stat blue cmp" value="<?php echo 'test'.$i; ?>" id="<?php echo 'test'.$i; ?>">
          <div class="visual">
           <i class="fa fa-comments"></i>
          </div>
          <div class="details ">
            <div class="desc" > akak</div>
          </div>
        </div>
      </div>
      <?php }?>
    </div>

When i am selecting div it should give value of cmp div.But when im selecting every time same value is coming.I am trying to get this value inside hidden text box.Below is my JS code. 当我选择div时,它应该给出cmp div的值。但是当我每次选择相同的值时,我正在尝试在隐藏文本框中获取此值。以下是我的JS代码。

$(".list").selectable({
    stop: function() {
     $(".cmp", this).each(function() {
      var index  =$(this).attr('data');
      console.log($('.cmp').attr('id'));
      items += ("," +(index));
     });
      $('#mod').val(items);
    }
}) 

Thanks in advance. 提前致谢。

You are using 您正在使用

$('.cmp').attr('id')

which will give you all div with class value having cmp and calling attr('id') will give you id of first div only. 这将为您提供具有cmp类值的所有div并调用attr('id')将仅为您提供第一个div的id。

As you are iterating through list of divs, you must use $(this) which will give you the current div in the loop as shown below 在遍历div列表时,必须使用$(this) ,它将为您提供循环中的当前div,如下所示

$(this).attr('id')

Consider looking into documentation at this URL: http://jqueryui.com/selectable/#serialize 考虑查看以下URL的文档: http : //jqueryui.com/selectable/#serialize

it will give you exactly what you need. 它会为您提供所需的确切信息。

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

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