获取每个html元素的.each

时间:2017-10-25 10:39:38

标签: javascript jquery asp.net-mvc

我希望在我的View(MVC)的foreach循环中每个按钮都可以工作,也就是渲染局部视图。但只有第一个按钮工作(渲染局部视图),而不是其余按钮。我没有打算从我的视图中粘贴代码,因为它只是一个带有渲染局部视图的代码的div。

以下是代码和我的想法:

<button class="myBtn btn btn-default"  onclick="location.href='@Url.Action("Edit", "Home", new { id = item.Id })'">
   Edit
</button>

Javascript(取自w3schools略有修改):

<script>
// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementsByClassName("myBtn");

$(btn).each(function () {
    for (var i = 0; i < btn.length; i++)
    {
        //btn[i].className = "myBtn";
        btn = btn[i];
    }
});

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on the button, open the modal
btn.onclick = function () {
    modal.style.display = "block";        
}

// When the user clicks on <span> (x), close the modal
span.onclick = function () {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function (event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

1 个答案:

答案 0 :(得分:0)

当你在循环中然后你改变了你的“btn”数组看下面的代码

// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementsByClassName("myBtn");
console.log(btn);

此输出应该是这样的数组enter image description here

$(btn).each(function () {
    for (var i = 0; i < btn.length; i++)
    {
        //btn[i].className = "myBtn";
        btn = btn[i];

当您设置数组输出并更改循环时,您可以看到此图像发生了enter image description here这个下面的console.log输出,您更改了数组并且无法遍历代码中的每个btn对象< / p>

        console.log(i)
    }
});
console.log(btn);