使用span标签更改div背景颜色onclick

时间:2014-08-27 16:00:20

标签: javascript jquery html css

我有以下HTML代码:

    <div id="parent" style="background-color:#FFFFFF">
     <ul>    
      <li><span data-color="red">Text 1</span></li>
      <li><span data-color="blue">Text 2</span></li>
      <li><span data-color="yellow">Text 3</span></li>
     </ul>
    </div>

如果我点击特定<span>,则应更改div父级的背景颜色。

如何使用jQuery完成此操作?

我试过这个:

$('ul li span').click(function(){
   $('.parent').css('background-color', $(this).data-color);
});

2 个答案:

答案 0 :(得分:4)

使用vanilla JavaScript(无库):

//We attach a click handler on the nearest common parent.
//This allows us to have only one event handler, which is better
//For performance!
document.getElementById("parent").onclick = function(e) {
    //We only want events on the spans, so let's check that!
    if (e.target.tagName.toLowerCase() == "span") { 
        this.style.backgroundColor = "#BADA55";
        //This is for the sake of example only!
        //TODO: A better approach would be to add a class
        //And define a CSS rule for that class.
    }
};

或没有评论

document.getElementById("parent").onclick = function(e) {
    if (e.target.tagname.toLowerCase() == "span") { 
        this.style.backgroundColor = "#BADA55";
    }
};

与jQuery等效:

$("#parent").on("span", "click", function() {
    $("#parent").css({backgroundColor: "#BADA55"});
});

<强> Example

答案 1 :(得分:-3)

$('ul li span').on('click',function(){
     $(this).closest('div').css('background-color',$(this).data('color'));
})

<div id="parent" style="background-color:#FFFFFF">
 <ul>    
  <li><span data-color='red'>Text 1</span></li>
  <li><span data-color='yellow'>Text 2</span></li>
  <li><span data-color='green'>Text 3</span></li>
 </ul>

这是演示http://jsfiddle.net/k6t80zsg/3/