问题描述
我想使用数据选择器写入全局变量。这甚至可能吗? (请温柔一点,我的经验很肤浅:)
var one = 0;
var two = 0;
var three = 0;
$("a[data-typ]").click(function() {
if ($(this).hasClass('active')) {
$(this).removeClass('active');
$(this).data("typ").toString--;
} else {
$(this).addClass('active');
$(this).data("typ").toString++;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a data-typ='one'>One</a>
<a data-typ='two'>Two</a>
<a data-typ='three'>Three</a>
解决方法
你是这个意思吗?
var one = 0;
var two = 0;
var three = 0;
$("a[data-typ]").click(function() {
const typ = $(this).data("typ")
if ($(this).is('.active')) {
window[typ]--
} else {
window[typ]++
}
console.log(one,two,three)
$(this).toggleClass("active");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a data-typ='one'>One</a>
<a data-typ='two'>Two</a>
<a data-typ='three'>Three</a>
如果您需要拆分一个属性中的多个数据类型:
var one = 0;
var two = 0;
var three = 0;
$("a[data-typ]").click(function() {
const types = $(this).data("typ").split(" "); // split on space.
const active = $(this).is('.active');
types.forEach(typ => {
if (active) {
window[typ]--
} else {
window[typ]++
}
})
console.log(one,three)
$(this).toggleClass("active");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a data-typ='one three'>One and three</a>
<a data-typ='two'>Two</a>
我正在尝试使用 div 和文本而不是链接上的属性进行计数。当然,由于我的新手,它不起作用。我做错了什么?
var one = 0;
var two = 0;
var three = 0;
$(".answer").click(function() {
const types = $(this).find("typ").text().split(" "); // split on space.
const active = $(this).is('.active');
types.forEach(typ => {
if (active) {
window[typ]--
} else {
window[typ]++
}
})
console.log(one,three)
$(this).toggleClass("active");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="answer">
<div class="typ">one three</div>
</div>
<div class="answer">
<div class="typ">two</div>
</div>