Javascript jquery:点击一个P,它的颜色会改变,点击另一个P,它';它的颜色会改变。单击第二个P时,是否更改第一个P的颜色?
我正在尝试访问之前单击的段落/元素。用户将单击一个段落,背景颜色从白色变为蓝色,这在视觉上意味着用户单击的P现在被选中。当他们点击不同的段落时,先前选择的段落的背景颜色会从蓝色变回白色 是否有方法选择以前单击的段落?最好不添加和删除类。显然,我下面的代码不起作用,但我已经解释了我认为答案可能是如何起作用的Javascript jquery:点击一个P,它的颜色会改变,点击另一个P,它';它的颜色会改变。单击第二个P时,是否更改第一个P的颜色?,javascript,jquery,selected,click,Javascript,Jquery,Selected,Click,我正在尝试访问之前单击的段落/元素。用户将单击一个段落,背景颜色从白色变为蓝色,这在视觉上意味着用户单击的P现在被选中。当他们点击不同的段落时,先前选择的段落的背景颜色会从蓝色变回白色 是否有方法选择以前单击的段落?最好不添加和删除类。显然,我下面的代码不起作用,但我已经解释了我认为答案可能是如何起作用的 $('p').bind('click', function () { //checks if an item was previously selected, if so, sets b
$('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)
})
css
html
如果没有类,则需要将变量存储在click handler函数范围之外:
// 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")
})
在
elm.addClass('higlight')中缺少一个“h”代码>
jQuery(function(){
jQuery('.highlightable').bind('click',function(){
var elm=jQuery(this);
if(elm.hasClass('highlight'))
{
elm.removeClass('highlight')
}
else
{
jQuery('.highlight').removeClass('highlight');
elm.addClass('highlight');
}
});
});
// 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")
})