单击后,我使用纯 javascript 为我的元素 (SVG PATH) 分配了一个类:
this.getElement().classList.add('active');
新类(class)是它已有的一系列其他类(class)的一部分。然而,一旦这个新类被添加到被点击的元素,它也应该为 html 中的其他元素提供一个 .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 将具有与任何按钮类匹配的任何类。
问题是,出于特定原因,我使用纯 javascript 在单击 div 时分配一个新类名(有效):
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');
}
但我在这之外还有按钮,需要根据问题激活一个类。
Desired after the div click
<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>
This is how I deal with the opposite, clicking on the buttons (and works):
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");
});
注意
In real life on the buttons I am using
data attribute
but consider it as a class for the example question on here, it's just a paste from a more complex code I have.Also I am using leafletsJS, that's why the javascript click in the function above.
最佳答案
一个选项是:
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/