有人能帮助我使用jQuery定位同一div中的选定项目吗?
以下是我对代码点火器的看法:
<?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())
})
根据您的代码,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());
})
})