更改被单击的id的背景

change the background of an id that is clicked

本文关键字:id 背景 单击      更新时间:2023-09-26

当一个表单的元素(id)被点击时,我想要监听该事件,并改变该元素的背景。

$(document).ready(function(){
    $('form').on('click', function(e){        
        var x = e.target.id;
        $(x).css('background-color',color);
        return false;
    });
}

<form>
  <div id="a">Item1</div>
  <div id="b">Item2</div>
  <div id="c">Item3</div>
</form>

由于选择器是

,您的代码将最终寻找标签名称
$("b")

如果你想按照你的方式来做,你需要添加缺失的#

$("#" + x).css('background-color',color);

但是,如果已经有对该元素的引用,则不需要查找该元素。使用事件委托和这个

$('form').on('click', 'div', function(e){        
    $(this).css('background-color',color);
});

为什么要用e.target呢?只需更新代码以使用$(this):

$(function() {  
    $('form > div').on('click', function(e) {  
        e.preventDefault();
        $(this).css('backgroundColor', color);
    });
});

这就行了。照顾好你的标签。

 $(document).ready(function(){
    $('form').on('click', function(e){   
        var x = e.target.id;
        $("#"+x).css('background-color',"red");
        return false;
    });
});

发生在您身上的事情是event.target.id返回一个表示元素id的字符串,而不是选择器。这里使用$(x)....你必须使用$('#'+x),你的实际代码不工作,因为选择器的背景变化是不寻找与Id上的x值的元素,但为一个元素称为像x的值(例如。X ="a",那么它在寻找元素)

这是我的"low "尝试:

<!DOCTYPE html>
<html lang = 'es'>
    <head>
        <title> My Test </title>
    </head>
    <body>
        <form>
          <div id="a"> Item1 </div>
          <div id="b"> Item2 </div>
          <div id="c"> Item3 </div>
        </form>
        <script>
            function addBackgroundColor(e){
                var index = parseInt(Math.random() * 4); // the number of the multiplier has to be equal to the length of the array colorsList.
                e.target.style.backgroundColor = colorsList[index];
            }
            var colorsList = ['blue','red','green','yellow','orange']; //add others colors here if you want.
            var divsList = document.getElementsByTagName('div');
            for (var i in divsList){
                divsList[i].addEventListener('click', addBackgroundColor);
            }   
        </script>
    </body>
</html>

不用太花哨。

$(document).ready(function(){
    $('form div').on('click', function(e){        
        $(this).css('background-color',color);
        return false;
    });
}