![](/img/trans.png)
[英]Creating dynamic button ID and sending the ID to a javascript function. Javascript function is not accepting
[英]how to sending Dynamic Id sending getElementById to js function
<div id="product-zoom-gallery" class="product-image-gallery">
@foreach (var item in Model.Images)
{
<a onclick="myFunction('@item')" class="product-gallery-item active" href="#" @*onclick="changeImg('/@item');"*@
data-image="/@item"
data-zoom-image="/@item">
<img id="myImg @item" src="/@item"
>
</a>
}
</div>
我想將動態 ID 發送到myFunction(item)
,其中“item”是我的動態 ID,我想像這樣將其發送到 getElementById 方法:
function myFunction(item){
var string = `"myImg ${item}"`
alert(string);
var modal = document.getElementById("myModal");
var img = document.getElementById(`"${string}"`);
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function () {
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function () {
modal.style.display = "none";
}
}
但是var img
對我不起作用。 我希望var img = document.getElementById(
"${string}" );
, 找到我的 img 標簽。
id
屬性不支持空格。 通常,您應該堅持使用字母數字 ASCII 友好字符(而不是以數字開頭)。 除了字母和數字,您還可以使用_
或-
作為分隔符。"
)(在反引號 `` 之間),因為反引號已經自動將其內容轉換為字符串。所以你可以變成:
<img id="myImg-item">
function myFunction(id){
var string = `myImg-${id}`
alert(string);
var modal = document.getElementById("myModal");
var img = document.getElementById(string);
現在,如果您調用您的函數: myFunction('item')
,它將組裝 ID "myImg-item"
並且 getElementById 查找應該會成功。
有關更多信息,請閱讀MDN 文檔上的id
屬性
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.