css文件
.clsA { ... }
.clsB { ... }
.clsC { ... }
...
...
js文件
var g = $('.gHead')
var res, last_key=''
var ca, cb, cc, cd, ....
ca = $('.clsA')
cb = $('.clsA')
cc = $('.clsA')
...
...
function nextV(a) {
var len = a.length
var choice = Math.floor(Math.random() * len) /* problem 1 */
res = a.filter(function (elm) {
return elm.key == a[choice].key
})
g.removeClass(res[0].key) /* problem 2 */
last_key = res[0].key /* got key */
}
function changeIt() {
var arr = []
arr.push({key: 'ca', value: ca})
arr.push({key: 'cb', value: cb})
...
...
nextV(arr)
if (res.length > 0) {
g.addClass(res[0].key) /* working */
console.log(g)
}
console.log('prevClass: '+ last_key) /* found prev added item */
}
$('.cng').on('click', function () {
changeIt()
})
我希望.gHead
每次点击.cng
必须仅附加一个类。像:下次单击.gHead .clsA
时应为.gHead .clsB
,依此类推。但是,我得到了:.gHead .clsA
>>[C0
.gHead .clsA .clsB
问题1:基于数组.gHead .clsA .clsB .clsC
索引,我想使其成为LinearChoice,而不是RandomChoice。但是,我不想使用arr
。
问题2:It-> arr.indexOf()
对输出没有影响。 g.addClass(...)几乎相反的地方都在工作!
我稍微清理了一下代码,在这里您可以看到删除类不起作用,因为您是从g.removeClass(res[0].key)
返回后立即将其添加回去的。
js文件
nextV()
要线性遍历键,您可以将var g = $('.gHead')
var ca, cb, cc, cd, ....
ca = $('.clsA')
cb = $('.clsA')
cc = $('.clsA')
...
...
var arr = [] // does not make sense to always recreate this
arr.push({key: 'ca', value: ca})
arr.push({key: 'cb', value: cb})
...
var choice = 0
function nextV() {
choice = Math.floor(Math.random() * arr.length) /* problem 1 */
// the filtering always leads to res being a single item array and res[0] being a[choice]
g.removeClass(arr[choice].key) /* problem 2 */
}
function changeIt() {
nextV()
// if (res.length > 0) { // this is always true in your code
g.addClass(arr[choice].key) /* working */
}
$('.cng').on('click', function () {
changeIt()
})
初始化为choice
而不是零,并在arr.length-1
中将选择计算为choice = (choice+1) % a.length
,而不是随机函数。
然后,您也可以在使用nextV
添加新的类(我认为这是您想要做的“问题2”之前,先删除上一个类)>
总结:根据您的描述,我不确定您的代码是否能达到您的期望,但是我希望这可以帮助您正确地理解它。
您可以使用g.removeClass(arr[(choice+arr.length-1)%arr.length].key)
将上一类存储在元素上,并在下次单击时将其检索以删除。>
由于您没有为完整示例提供足够的标记,因此这是一个基本示例
如果您的类.gHead有多个元素,则可以使用此选项>
.a{ color:red}
.b{color:blue}
.c{color:green}
li{padding:.5em}
如果要基于数组更改ONE元素上的css类(如charlietfl指出的,请执行以下操作:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>Click to change class</li>
<li>Click to change class</li>
<li>Click to change class</li>
<li>Click to change class</li>
</ul>