【问题标题】:Find and remove style attribute on click单击时查找并删除样式属性
【发布时间】:2015-08-30 03:13:51
【问题描述】:

当单击相应的标签时,我试图从表中的单个 tr 标签中删除样式属性。一直在尝试一些代码,但找不到解决方案。

这里是小提琴:http://jsfiddle.net/q2nb08t6/12/ jQuery:

$(".tr_table").click(function(){

$(".tg_table").removeAttr('style');
//$(".tg_table").parent().find("tg_table").removeAttr('style');    
//$(".tg_table").parent().removeAttr('style');
//$(".tg_table").each().removeAttr('style');
});

【问题讨论】:

  • 样式在table节点上,不在tr节点上。
  • 是的对不起我的错误

标签: javascript jquery


【解决方案1】:
  1. 改变你的方法。在tr 级别而不是table 级别上应用该样式
  2. 点击时使用removeClass() 删除类。 或者,您可以在点击时使用toggleClass() 切换类。

$(".tr_table").click(function() {
  $(this).toggleClass('tr_table');
});
.tg_table {
  width: 100%
}
.tr_table {
  cursor: pointer;
}
tr.tr_table {
  background-color: rgba(255, 0, 0, 0.5) !important;
  color: white !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<table class="tg_table" border="1" style="">
  <tr class="tr_table">
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr class="tr_table">
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
  <tr class="tr_table">
    <td>Neil</td>
    <td>Mark</td>
    <td>30</td>
  </tr>
  <tr class="tr_table">
    <td>Mike</td>
    <td>Ford</td>
    <td>98</td>
  </tr>
</table>

更新

很遗憾,由于表格是由 php 脚本生成的,因此我无法更改方法

在这种情况下,您可以使用css() 更改tr 样式

$(".tr_table").click(function() {
  $(this).css('background', 'white');
  $(this).css('color', 'black');
});
.tg_table {
  width: 100%
}
.tr_table {
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table class="tg_table" border="1" style="background-color: rgba(255,0,0,0.5) !important;color:white !important;">
  <tr class="tr_table">
    <td>Jill</td>
    <td>Smith</td> 
    <td>50</td>
  </tr>
  <tr class="tr_table">
    <td>Eve</td>
    <td>Jackson</td> 
    <td>94</td>
  </tr>
    <tr class="tr_table">
    <td>Neil</td>
    <td>Mark</td> 
    <td>30</td>
  </tr>
    <tr class="tr_table">
    <td>Mike</td>
    <td>Ford</td> 
    <td>98</td>
  </tr>
</table>

【讨论】:

  • 不幸的是我无法更改方法,因为该表是由 php 脚本生成的
【解决方案2】:

据我所知,here,除非您覆盖它,否则您无法删除从父级继承的样式。这里最好的解决方案是找到一个默认样式,然后在单击行时设置此样式,这将删除父样式。

这里的代码,$(this) 指的是被点击的元素。

$(".tr_table").click(function(){
    $(this).attr('style','background-color: rgba(255,255,255,0.5) !important;color:white !important;');
});

【讨论】:

    猜你喜欢
    • 2019-06-19
    • 1970-01-01
    • 1970-01-01
    • 2013-02-02
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多