gpt4 book ai didi

javascript - 如何在 div 中放置一个按钮,其中数据通过 $.each 函数动态填充

转载 作者:行者123 更新时间:2023-12-03 08:02:41 25 4
gpt4 key购买 nike

这应该很简单,但我在这里很挣扎。

我有一个父 div,它有多个子 div。这些子div是根据$.each()函数生成的。函数运行的次数,生成的 div 数量。现在,我想在单击按钮时编写一个服务器端函数,但我无法在这些子 div 中列出该按钮。

<div class="div1">
<div class="div2">
// this is the button which i cant see in my div2 div
<button type="input">follow</button>
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("/Home/GetUsers", null, function(data) {
$(".div1").html("");
$.each(data, function(i, item) {

var html = "<div class='div2'>";
html += "Name: " + item.UserName + "<br />";
html += item.ArticleCount;
html += "<img src='" + item.UserImage + "'height='20px' width='20px'/>"
html += "</div>";
$(".div1").append(html);
});
});
});
</script>
</div>
</div>

感谢任何类型的指导。

最佳答案

如果您想为每个子 div 添加一个按钮,您可以这样做:

 $(document).ready(function() {
var parent = $(".div1");

$.getJSON("/Home/GetUsers", null, function(data) {

parent.html("");

$.each(data, function(i, item) {

var html = "<div class='div2'>";
html += "Name: " + item.UserName + "<br />";
html += item.ArticleCount;
html += "<img src='" + item.UserImage + "'height='20px' width='20px'/>";
html += "<button type='button' class='newButton'>Click Me!</button>";
html += "</div>";

parent.append(html);
});

});

// In order to ensure that the button click is handled no matter when it was
// added, we can delegate the handler to the parent.

parent.on('click', '.newButton', function(e) {
var button = $(this);

// Handle the individual button click server side call here.
});
});

关于javascript - 如何在 div 中放置一个按钮,其中数据通过 $.each 函数动态填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34525633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com