如何从jQuery中的同名div获取当前选定的div元素?

问题描述 投票:1回答:1

[有人可以帮助我使用jQuery定位来自同一div的选定项目吗?

这是我在codeigniter中的观点:

<?php 

 foreach($operator as $Operator) {
 ?>
 <div id="default">
                <div class="col-xl-12 col-md-12 mb-4">
                  <div class="card border-left-danger shadow h-100 py-2">
                    <div class="card-body">
                      <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                          <div class="text-xs font-weight-bold text-warning text-uppercase mb-1" id="countryName"><?=@$Operator->country?></div>
                          <div class="h5 mb-0 font-weight-bold text-gray-800" id="operatorname"><?=@$Operator->longName?></div>
                        </div>
                        <div class="col-auto" id="operatorImage">
                            <img src="https://imagerepo.ding.com/logo/<?=strtoupper(substr(@$Operator->providerCode,0,2))?>.png"/>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <input type="hidden" name="countryIso" value="<?=$Operator->countryIso?>">
</div>
    <?php }?>


在div上方创建不同的卡片,我希望在单击卡片时向我显示被点击卡片的内容

但是我在下面尝试过选择第一个元素而不是其他元素

jQuery代码:

$("#default").click(function(event){

    alert($(this,"#operatorname").text())

})
javascript jquery codeigniter codeigniter-3
1个回答
1
投票

根据您的代码,html中将有多个相同的id,这是一种不好的做法。

考虑如下更正您的代码:

 <?php  foreach($operator as $index => $Operator):?>
 <div id="default<?= '_' . $index ?>" class="operator-card">
                <div class="col-xl-12 col-md-12 mb-4">
                  <div class="card border-left-danger shadow h-100 py-2">
                    <div class="card-body">
                      <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                          <div class="text-xs font-weight-bold text-warning text-uppercase mb-1" class="countryName"><?=@$Operator->country?></div>
                          <div class="h5 mb-0 font-weight-bold text-gray-800" class="operatorname"><?=@$Operator->longName?></div>
                        </div>
                        <div class="col-auto" class="operatorImage">
                            <img src="https://imagerepo.ding.com/logo/<?=strtoupper(substr(@$Operator->providerCode,0,2))?>.png"/>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <input type="hidden" name="countryIso" value="<?=$Operator->countryIso?>">
</div>
    <?php endforeach; ?>

然后使用javascript:


$(document).ready(function() {
    $(".operator-card").on('click', function() {
        alert($(this).find('.operatorname').text());
    })
})

© www.soinside.com 2019 - 2024. All rights reserved.