jQuery如何区分动态ID?
HTML:
@foreach($listeSeances as $seance)
...
<div class="modal fade reservationModal" id="reservationModal-{{ $seance->id_seance }}" tabindex="-1" role="dialog" aria-labelledby="reservationModal-{{ $seance->id_seance }}" aria-hidden="true">
...
</div>
@endforeach
JS:
$('[id^="reservationModal-"]').on('shown.bs.modal', function (e) {
console.log('works');
});
我的目标是找到如何用JS中的任何数字“替换”
{{ $seance->id_seance }}
以具有通用功能。感谢帮助!
最佳答案
shown.bs.modal
事件的目标是div.modal
,您可以从中检索元素ID –只需进行一点分析,就可以在插入id_seance
之前获取其原始值。
$('[id^="reservationModal-"]').on('shown.bs.modal', function (e) {
let id_seance = e.target.id.split('-').pop(-1);
console.log('works', { id_seance });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#reservationModal-1">
Reservation 1
</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#reservationModal-2">
Reservation 2
</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#reservationModal-3">
Reservation 3
</button>
<div class="modal fade reservationModal" id="reservationModal-1" tabindex="-1" role="dialog" aria-labelledby="reservationModal-1" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Reservation 1</h5>
</div>
</div>
</div>
</div>
<div class="modal fade reservationModal" id="reservationModal-2" tabindex="-1" role="dialog" aria-labelledby="reservationModal-2" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Reservation 2</h5>
</div>
</div>
</div>
</div>
<div class="modal fade reservationModal" id="reservationModal-3" tabindex="-1" role="dialog" aria-labelledby="reservationModal-3" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Reservation 3</h5>
</div>
</div>
</div>
</div>
关于javascript - 区分动态ID,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47959963/