设置按钮以添加 <TD> ID# 中的文本类别?



我有一个表。第一列是用户可编辑的文本(ID #idea01),接下来的两列有一个按钮,每个按钮都有自己的单独ID (#happy01 &#unwanted01):

<!DOCTYPE html>
<body>
    <p>Step 1: Write a list</p>
        <table border="0">
            <tr>
                <td id="idea01" contenteditable="true">&#149; [delete this and enter your idea]</td>
                <td><button id="happy01">happy to do this for life</button></td>
                <td><button id="unwanted01">unwanted dependency</button></td>
            </tr>
        </table>
<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/script.js"></script>
    </body>
</html>

这个想法是,用户可以编辑第一列文本,然后单击任意一个按钮,CSS将显示哪些想法是"。快乐"和哪些想法是"不需要的"。

CSS类格式很简单,只适用于文本:

.happy { color: green; font-weight: bold;}
.unwanted { color: red; text-decoration: line-through;}

我的问题:我如何使用jQuery,点击按钮#happy01, .happy类添加到TD与ID #idea01 ?或者,点击按钮#unwanted01, .unwanted类被添加到TD #idea01 ?

我认为这将工作,但点击按钮不做任何事情:

$("#happy01").click(function(){
  $("#idea01").addClass("happy");
});
$("#unwanted01").click(function(){
  $("#idea01").addClass("unwanted");
});

谢谢你的帮助!

你的代码是正确的,只是删除另一个类。

$("#happy01").click(function(){
  $("#idea01").addClass("happy");
  $("#idea01").removeClass("unwanted");
});
$("#unwanted01").click(function(){
  $("#idea01").addClass("unwanted");
  $("#idea01").removeClass("happy");
});

最新更新