这是基本上打开和关闭div的jQuery代码:
jQuery('#filter_werk').find('.raven-sortable').addClass('opened');
var toggle = document.getElementById('deknop');
var slider = document.querySelector('.raven-sortable');
toggle.addEventListener('click', toggleSlider, false);
function toggleSlider(){
if (slider.classList.contains('opened')) {
slider.classList.remove('opened');
slider.classList.add('closed');
} else {
slider.classList.remove('closed');
slider.classList.add('opened');
}
}
</script>
我想做的是将以下div的内容从“ FILTER +”更改为“ FILTER-”,然后再次单击时再次返回“ FILTER +”
<div id="deknop">FILTER +</div>
可以在不破坏当前jQuery代码的情况下完成此操作吗? 谢谢!
答案 0 :(得分:1)
据我了解,功能toggleSlider
可以正常工作,所以请尝试:
function toggleSlider(){
if (slider.classList.contains('opened')) {
slider.classList.remove('opened');
slider.classList.add('closed');
toggle.innerHTML = "FILTER +";
} else {
slider.classList.remove('closed');
slider.classList.add('opened');
toggle.innerHTML = "FILTER -";
}
}
答案 1 :(得分:0)
您可以在toggleSlider()
函数中添加一些逻辑,这些逻辑将根据当前文本来更改#deknop
文本(“ FILTER +”或“ FILTER-”,如下所示:
function toggleSlider(){
$('#deknop').html($('#deknop').text() == 'FILTER +' ? 'FILTER -' : 'FILTER +');
if (slider.classList.contains('opened')) {
slider.classList.remove('opened');
slider.classList.add('closed');
} else {
slider.classList.remove('closed');
slider.classList.add('opened');
}
}
答案 2 :(得分:0)
好吧
如果我必须执行这种jQuery样式,则我会以两种方式尝试从视图中分离数据。像这样:
(() => {
const state = {
sliderOpen: true,
};
const $slider = $('.raven-sortable');
const $toggle = $('#deknop');
const updateView = () => {
if (state.sliderOpen) {
$slider.addClass('opened').removeClass('closed');
} else {
$slider.addClass('closed').removeClass('opened');
}
$toggle.text(`FILTER ${state.sliderOpen ? '+' : '-'}`);
};
const onToggleClick = () => {
state.sliderOpen = !state.sliderOpen;
updateView();
};
$toggle.click(onToggleClick);
updateView();
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="raven-sortable">Raven sortable</button>
<button id="deknop"></button>