【问题标题】:How to change colour of an element when radio button is checked选中单选按钮时如何更改元素的颜色
【发布时间】:2019-02-23 00:15:47
【问题描述】:

页面的工作原理:
用户填写注册表(姓名、姓氏、年龄......)。 管理员可以查看所有这些值,并通过单击相应的单选按钮来批准或拒绝每个值。

我想要什么:
在我的 .phtml 文件中,我有一个循环,它产生不同的单选按钮组(1 组用于名称字段,1 组用于姓氏等)。 每个单选按钮都有不同的 ID。 每个单选按钮组对应于页面中的不同元素(姓名,姓氏...)。 如何检查每组 2 个单选按钮中的哪一个被选中,并更改其对应元素(姓名、姓氏...)的背景颜色?

到目前为止我做了什么:
我可以使它工作的唯一方法是实际单击单选按钮并获取它的 ID。然后通过使用'data-html'指令,我改变了相应字段的颜色。
我尝试将 .click 函数更改为 .checked 但我不知道如何获取我需要的 ID。

$(document).ready(function () {
    $('.radio-approved').click(function(){
        greenColor($(this));
    });

    $('.radio-rejected').click(function(){
        redColor($(this));
    });
});

function greenColor(button) {

    var correspondingField=document.getElementById(button.data('html'));

    $(correspondingField).css({
        "background-color": "green"
    });
}

function redColor(button) {

    var correspondingField=document.getElementById(button.data('html'));

    $(correspondingField).css({
        "background-color": "red"
    });
}

【问题讨论】:

  • 为什么不能使用 CSS 为特定类设置背景颜色?
  • 首先,由于使用的是jquery,所以不需要使用纯js方法getElementById()
  • @ygorbunkov 为什么不呢?我经常将两者混合在一起,因为一些原生 js 的东西比它的 jquery 替代品更快、更有效——仅仅因为你使用 jQuery 并不意味着你应该忽略原生 js,如果它在某些情况下更好(在这里授予它似乎被浪费了) )
  • @user1597430 嗯,我不太明白你的意思。请您详细说明一下吗?
  • @Ranga 经典的方法是为特定的类创建 CSS 样式,并仅使用 JS 从元素中添加或删除类。

标签: javascript jquery html radio-button


【解决方案1】:

你是这个意思吗?

$('[type="radio"][name="status"]').on('change', event => {
  $(event.target).closest('tr').css('background-color', $(event.target).val() == 'approve' ? 'green' : 'red')
});
td {width:150px;text-align:center}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>Name</th><th>Lastname</th><th>Status</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Kevin</td><td>Spacey</td><td><input type="radio" value="approve" name="status">approve</input><input type="radio" value="reject" name="status">reject</input></td>
    </tr>
      <td>Nicolas</td><td>Cage</td><td><input type="radio" value="approve" name="status">approve</input><input type="radio" value="reject" name="status">reject</input></td>
    </tr>
      <td>Robert</td><td>Downey</td><td><input type="radio" value="approve" name="status">approve</input><input type="radio" value="reject" name="status">reject</input></td>
    </tr>
      <td>Chris</td><td>Evans</td><td><input type="radio" value="approve" name="status">approve</input><input type="radio" value="reject" name="status">reject</input></td>
    </tr>
  </tbody>
</table>

【讨论】:

    猜你喜欢
    • 2014-05-27
    • 2015-02-24
    • 1970-01-01
    • 2018-11-20
    • 2011-05-14
    • 1970-01-01
    • 1970-01-01
    • 2017-09-21
    相关资源
    最近更新 更多