1

我正在尝试访问先前单击的段落/元素。用户将点击一个段落,bg-color 从白色变为蓝色,视觉上这对用户意味着他们点击的 P 现在被选中了。当他们点击不同的段落时,之前选择的段落的背景颜色会从蓝色变回白色。

有没有办法选择以前点击的段落?最好不添加和删除类。显然我下面的代码不起作用,但我已经解释了我认为答案可能如何工作?

$('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)
})
4

2 回答 2

2

如果没有类,您需要将变量存储在点击处理函数范围之外:

// 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")
})
于 2011-03-10T06:25:53.457 回答
0

css

.highlight
{
background-color:yellow;
}

html

<p class="highlightable"></p>
<p class="highlightable"></p>
<p class="highlightable"></p>

Javascript

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');
           }
   });
});

演示

于 2011-03-10T06:24:19.543 回答