我正在寻找一种更好的方法来重写一个简单的显示/隐藏 jQuery 切换,它可以允许基于使用 div 选择器的实现;并且无需修改 HTML 标记(因此无需添加类 .hidden
等)
我有一系列类为 .djseform_field
的 div,其中没有其他选择器;寻求仅使用这个类将这些 div 转换为显示/隐藏 jQuery 切换。
最佳答案
可能是这样的:
$(document).ready(function() {
// choose text for the show/hide link
var showText='read more...';
var hideText='hide';
// initialise the visibility check
var isVisible = false;
// append show/hide links to the element directly preceding the element with a class of "djseform_field"
$('.djseform_field').prev().append(' <a href="#" class="toggleLink">'+showText+'</a>');
// hide all of the elements with a class of 'djseform_field'
$('.djseform_field').hide();
// capture clicks on the toggle links
$('a.toggleLink').click(function() {
// switch visibility
isVisible = !isVisible;
// change the link depending on whether the element is shown or hidden
if ($(this).html()==showText) {
$(this).html(hideText);
}
else {
$(this).html(showText);
}
// toggle the display
$(this).parent().next('.djseform_field').slideToggle('slow');
// return false so any link destination is not followed
return false;
});
});
关于javascript - 在不访问标记的情况下实现 jquery 显示/隐藏切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26292009/