有一个很具体的情况,有一定数量的帖子(比如10个),还有两个按钮:删除,查看。我们需要View按钮来使用data-id重定向用户,但这很好,但按钮位置很糟糕。此外,每个帖子都有一个带有自己id的图像,也许以这种方式重定向用户会更好?
// viewLinkID - значение атрибута data-id
$('span').each(function() {
$(this).append('<button><a href=' + viewLinkID + '> [ View ]</button>')
}
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<title>Redirect by using element's Data-ID</title>
</head>
<body style="background: white;">
<h2>Posts</h2>
<div data-id="1">
<h4>Post 1</h4>
<img src=..posts/images/1.jpg>
<span>Hello World</span>
<div class="buttons">
<span class="spbuttons">
<button onclick="delete();"> [ Delete ]</button>
</span>
</div>
</div>
<div data-id="2">
<h4>Post 2</h4>
<img src=..posts/images/2.jpg>
<span>Hello World</span>
<div class="buttons">
<span class="spbuttons">
<button onclick="delete();"> [ Delete ]</button>
</span>
</div>
</div>
<div data-id="3">
<h4>Post 3</h4>
<img src=..posts/images/3.jpg>
<span>Hello World</span>
<div class="buttons">
<span class="spbuttons">
<button onclick="delete();"> [ Delete ]</button>
</span>
</div>
</div>
<div data-id="4">
<h4>Post 4</h4>
<img src=..posts/images/4.jpg>
<span>Hello World</span>
<div class="buttons">
<span class="spbuttons">
<button onclick="delete();"> [ Delete ]</button>
</span>
</div>
</div>
<div data-id="5">
<h4>Post 5</h4>
<img src=..posts/images/5.jpg>
<span>Hello World</span>
<div class="buttons">
<span class="spbuttons">
<button onclick="delete();"> [ Delete ]</button>
</span>
</div>
</div>
<div data-id="6">
<h4>Post 6</h4>
<img src=..posts/images/6.jpg>
<span>Hello World</span>
<div class="buttons">
<span class="spbuttons">
<button onclick="delete();"> [ Delete ]</button>
</span>
</div>
</div>
<div data-id="7">
<h4>Post 7</h4>
<img src=..posts/images/7.jpg>
<span>Hello World</span>
<div class="buttons">
<span class="spbuttons">
<button onclick="delete();"> [ Delete ]</button>
</span>
</div>
</div>
<div data-id="8">
<h4>Post 8</h4>
<img src=..posts/images/8.jpg>
<span>Hello World</span>
<div class="buttons">
<span class="spbuttons">
<button onclick="delete();"> [ Delete ]</button>
</span>
</div>
</div>
<div data-id="9">
<h4>Post 9</h4>
<img src=..posts/images/9.jpg>
<span>Hello World</span>
<div class="buttons">
<span class="spbuttons">
<button onclick="delete();"> [ Delete ]</button>
</span>
</div>
</div>
<div data-id="10">
<h4>Post 10</h4>
<img src=..posts/images/10.jpg>
<span>Hello World</span>
<div class="buttons">
<span class="spbuttons">
<button onclick="delete();"> [ Delete ]</button>
</span>
</div>
</div>
</body>
</html>
顺便说一句,获取data-id的最佳方法是什么?通过方法data()
还是attr()
?如果代码中有任何错误,请指出并纠正我。
最终,“删除”按钮应该有一个“查看”按钮,可以重定向到当前帖子(在当前 ID/号码下发布)。
目标是首先<div>
获取 的值data-id
,并使用该值在“删除”按钮旁边创建一个按钮,并为每个<div>
.
更好通过
data()
,更清晰