我正在尝试访问之前单击的段落/元素。用户将单击一个段落,bg-color 从白色变为蓝色,视觉上这对用户意味着他们单击的 P 现在已被选中。当他们点击不同的段落时,先前选择的段落的 bg-color 从蓝色变回白色。
有没有办法选择之前点击的段落?最好不要添加和删除类。显然我下面的代码不起作用,但我已经解释了我认为答案可能如何起作用?
$('p').bind('click', function () {
//checks if an item was previously selected, if so, sets background back to white
$(previouslySelected).css({'backgroundColor':'white'})
//change the current background blue, then store this item for the next click
$(this).css({'backgroundColor':'blue'})
var previouslySelected = $(this)
})
最佳答案
如果没有类,您需要将变量存储在点击处理函数范围之外:
// on page load + wrapped in another function to avoid polluting global namespace
$(document).ready(function() {
var previouslySelected
$('p').bind('click', function () {
//checks if an item was previously selected, if so, sets background back to white
$(previouslySelected).css({'backgroundColor':'white'})
//change the current background blue, then store this item for the next click
$(this).css({'backgroundColor':'blue'})
previouslySelected = $(this)
})
})
不过添加类要简单得多:
$('p').bind('click', function () {
$("p.selected").removeClass("selected")
$(this).addClass("selected")
})
关于javascript - jquery:点击一个P,它的颜色发生变化,点击另一个P,它的颜色发生变化。点击2nd P时,改变第一个P的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5256130/