簡體   English   中英

如何發送動態ID發送getElementById到js函數

[英]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 標簽。

  1. id屬性不支持空格。 通常,您應該堅持使用字母數字 ASCII 友好字符(而不是以數字開頭)。 除了字母和數字,您還可以使用_-作為分隔符。
  2. 模板文字中有一些多余的引號 ( " )(在反引號 `` 之間),因為反引號已經自動將其內容轉換為字符串。

所以你可以變成:

<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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM