单击时,我使用纯JavaScript将一个类分配给我的元素(SVG PATH):
this.getElement().classList.add('active');
新类是它已经拥有的一系列其他类的一部分。但是,一旦将此新类添加到clicked元素中,它还应该为html中具有与clicked元素本身具有任何匹配类的其他元素提供
.active
类。的HTML:
<button class="1600 1500"></button>
<button class="1600 1300 1200"></button>
<button class="1300 1200 1700 1800"></button>
<button class="1300 1200 1100 1900"></button>
<div class="1600 1700 item leaflet"></div>
我不知道哪个按钮具有匹配的类,因为这些类也是动态的。我所知道的是,div将具有与任何按钮的类匹配的任何类。
事实是,出于特定原因,我在点击div时就使用了纯JavaScript来分配新的类名(是):
this.getElement().classList.add('active');
因此,以下操作将无效:
this.click(function() {
var classes = this.attr('class').split(' ')
classes.forEach(function(elem) {
$('.' + elem).addClass('active');
});
});
这就是我所说的点击:
function onEachFeature(feature, layer) {
layer.on({
click: panelShow
});
}
function panelShow(e) {
// This works, the class is added to the clicked element
this.getElement().classList.add('active');
}
但是我在此之外还有其他按钮,需要根据问题激活一个类(class)。
<div class="1600 1700 item leaflet active"></div>
<button class="1600 1500 active"></button>
<button class="1600 1300 1200 active"></button>
<button class="1300 1200 1700 1800 active"></button>
<button class="1300 1200 1100 1900"></button>
var date;
$("button").on("click", function(b) {
date = $(this).attr("data-date");
$('path').attr('class', function(index, classNames) {
return classNames.replace('active', '');
});
$("svg ." + date).attr('class', function(index, classNames) {
return classNames + ' active';
});
$(".btn").removeClass("active");
$(this).addClass("active");
});
注意
最佳答案
一种选择是:
var buttons = [].slice.call(document.querySelectorAll('.buttons button'));
function panelShow(e) {
$("path").removeClass("active");
var clickedPath = this.getElement();
clickedPath.classList.add("active");
var datum = (clickedPath.getAttribute('class').match(/\d+/g) || [])[0];
buttons.forEach(function(btn) {
var method = btn.getAttribute('data-date') === datum ? 'add' : 'remove';
btn.classList[method]('active');
});
}
关于javascript - 将JavaScript与jQuery混合,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40441754/