我有許多小影像,我正在使用 HTML 渲染它們。當用戶單擊影像時,它們接下來會在大尺寸的模態正文中打開。由于我需要動態更改模態主體的內容,例如,當單擊 Picture1.jpg 時,模態主體應包含 picture1.jpg,反之亦然。
但是,我不確定如何在<a>標簽或<img>標簽上觸發 onclick 事件以獲取一些有助于我識別點擊了哪個影像的資訊。
<a href="images/Picture1.jpg" data-bs-toggle="modal" data-bs-target="#exampleModal">
<img src="images/Picture1.jpg" alt="image not available">
</a>
<a href="images/Picture1.jpg" data-bs-toggle="modal" data-bs-target="#exampleModal">
<img src="images/Picture2.jpg" alt="image not available">
</a>
模態
<div class="modal-body">
<img src="images/Picture1.jpg" alt="image not available" id="imagepreview" style="width:100%; height: 100%;" >
</div>
uj5u.com熱心網友回復:
您可以event.target在純 javascript 中使用,$(this)如果您想使用 Jquery。
//Plain Javascript
document.getElementsByTagName('img')[0].addEventListener("click", function(event) {
console.log(event.target.src);
});
//Jquery
$('img').click(function() {
console.log($(this).attr('src'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://picsum.photos/200">
uj5u.com熱心網友回復:
我會使用 aButton因為你實際上并沒有鏈接,你正在執行一個 JS 功能。然后我會向按鈕添加一個事件偵聽器,src根據button的data-src值更新目標影像。
const buttonList = document.getElementsByClassName('target-button');
const modalImg = document.getElementById('imagepreview');
const processImg = (imgSrc) => () => {
modalImg.src = imgSrc;
};
Array.from(buttonList).forEach((button) => {
const buttonImgSrc = button.dataset.src;
button.addEventListener('click', processImg(buttonImgSrc))
});
<button class="target-button" data-src="images/Picture1.jpg" data-bs-toggle="modal" data-bs-target="#exampleModal">
<img src="images/Picture1.jpg" alt="image not available" />
</button>
<button class="target-button" data-src="images/Picture2.jpg" data-bs-toggle="modal" data-bs-target="#exampleModal">
<img src="images/Picture2.jpg" alt="image not available" />
</button>
<img src="" alt="image not available" id="imagepreview" style="width:100%; height: 100%;" />
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/338600.html
標籤:javascript html 查询 事件 引导模式
上一篇:如何創建一個包含資料屬性的每個字母以及該字母的位置的物件
下一篇:使用jQuery顯示一個選項
