I made this script, and despite one oddity, it works fine. It's hiding/showing the parent of div element with a class containing specific content. The problem when I press my <a>
elements, that act as buttons, they "filter" the divs, but it leaves the first comment <a>
? If I change the element do a <div>
instead no problem, but with an <a>
element it behaves weirdly? Is this just a bug or?
here is a JSFiddle: https://jsfiddle.net/g1puxhs7/2/
HTML:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<a class='viewBtn'>Published<a>
<a class='viewBtn'>Completed<a>
<a class='viewBtn'>Created<a>
<div class="orders" id="orders">
<div class="row">
<div class="status">
Completed
</div>
<a>Comment</a>
</div>
<div class="row">
<div class="status">
Completed
</div>
<a>Comment</a>
</div>
<div class="row">
<div class="status">
Completed
</div>
<a>Comment</a>
</div>
</div>
<style>
.row {
width: 200px;
margin: 10px;
background: #ccc;
padding: 4px;
}
</style>
SCRIPT:
//--Filter by Status--//
$('.viewBtn').click(function() {
var txt = $(this).text();
$('.status:contains("' + txt + '")').parent().toggle();
$(this).toggleClass('down');
});
答案 0 :(得分:2)
问题在于你的链接:
<a class='viewBtn'>Published<a>
<a class='viewBtn'>Completed<a>
<a class='viewBtn'>Created<a>
您有6个开放a
标记,而不是3个开放标记和3个结束标记。
这就是为什么浏览器会在您的脚本中在一堆地方添加结束a
标记,其中一个位于您的第一个div
中 - 然后您的整个DOM树看起来与您想要的不同。
答案 1 :(得分:1)
您的标记需要清理。这是你的标记清理。此外,我发现最好为你的锚标签添加href,然后你可以用#评论它们,或者你可以添加javascript:void(0)。如果您在JS中使用#approach,则可以添加e.preventDefault();
HTML Cleaned:
<div>
<a class='viewBtn' href="#">Published</a>
<a class='viewBtn' href="#">Completed</a>
<a class='viewBtn' href="#">Created</a>
</div>
<div class="orders" id="orders">
<div class="row">
<div class="status">
Completed
</div>
<a class="stuff" onclick="Comment">Comment</a>
</div>
<div class="row">
<div class="status">
Completed
</div>
<a class="stuff">Comment</a>
</div>
<div class="row">
<div class="status">
Completed
</div>
<a class="stuff">Comment</a>
</div>
</div>
JS with preventDefault():
$('.viewBtn').click(function(e) {
e.preventDefault();
var txt = $(this).text();
$('.status:contains("' + txt + '")').parent().toggle();
$(this).toggleClass('down');
});