【问题标题】:Use a span tag to change div background-color onclick [closed]使用 span 标签更改 div 背景颜色 onclick [关闭]
【发布时间】:2014-08-27 16:00:20
【问题描述】:

我有以下 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>

如果我点击特定的&lt;span&gt;,则应该更改 div 父级的背景颜色。

如何使用 jQuery 做到这一点?

我试过了:

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

【问题讨论】:

  • 你的 js 代码在哪里,你遇到了什么问题? SO不是写代码服务,需要自己先尝试一下
  • 我还没有,我对 jquery 很陌生
  • @RafaelMoraisdosSantos 该网站适用于尝试过某些事情并需要帮助的人。有太多好的教程可以教你这个。本网站的成员被假定为“专业人士”,但我们想要的只是那些提出问题的人的简单尝试,无论他们的技能水平如何。试试吧,我们不能因为你付出了很大的努力而责怪你。
  • 好的,我会尝试做点什么
  • @RafaelMoraisdosSantos 在您的代码中出现错误,您使用的是类选择器而不是 id 选择器。并且 $(this).data-color 必须更改为 $(this).data('color') 检查我的答案或小提琴jsfiddle.net/k6t80zsg/2

标签: javascript jquery html css


【解决方案1】:

使用原生 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.
    }
};

或者没有 cmets

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

【讨论】:

    【解决方案2】:
    $('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/

    【讨论】:

    • 我想向他展示最接近方法的用法。我们可以使用 id 直接改变颜色。但是如果他有多个具有相同结构的元素,我更喜欢最接近的方法,这就是给出示例的原因
    • 您的评论很有帮助,谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-27
    • 1970-01-01
    • 1970-01-01
    • 2010-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多