2016-03-03 122 views
0

昨天我问了一个问题(Button That When Clicked Will Display Hidden Column in HTML Table)。这个名字是不言而喻的,然而,在尝试新事物几小时后,我决定研究一种不同的方法。以下是想出了:将元素追加到元素

  • 一个按钮,点击后一个新类追加到元素
  • 通过这样做的时候,我们将在CSS
  • 使用“显示”功能切换列的知名度

我有以下HTML元素:

echo "<td class =\"development\" id = 'tag$i'>test1</th>"; 
echo "<td class =\"development\" id = 'tag$i'>test2</th>"; 
echo "<td class =\"development\" id = 'tag$i'>test3</th>"; 

$ i是行号,以便画面中的每个这些<td>的被包裹一个for循环内以创建一个列。

用CSS:

.development{ 
    text-align:center; 
    padding-left:10px; 
    display:block; 
} 

.hide{ 
    display:none; 
} 

因此,这是我需要你的帮助。我提出了一个按钮,点击后会运行一个JavaScript函数,它可以将'.hide'类附加到td标签。

<button onclick="addCss()">Click me</button> 

我不知道如何编写JavaScript,如果我需要传递任何参数,如ID的为<td>标签。后的第一个“为附加类名是重要的空间:

回答

1
document.getElementById('yourId').className += ' ClassName' 

//To select elements by class name. 
document.getElementsByClassName('yourId') 

注意。

为什么? :如果您的班级名称为“class1”并附加了“class2” - 它将导致“class1class2”

通过添加空格,它将导致“class1 class2”并被识别为两个单独的类。

<button onclick="document.getElementById('yourId').className += ' ClassName';">Click me</button> 

如果你想做出更好的解决方案。

<script> 

function addCss(element) { 
document.getElementById(element).className += ' ClassName'; 
} 

</script> 

然后,只需调用函数像你这样原本。您甚至可以为类名称本身添加一个参数。

+0

看起来像这种方法只允许我追加隐藏类只有一个'​​'标签 – anderish

+0

@ user3272303每个​​是否有相同的ID?我假设id ='tag $ i'每次递增,因此应用不同的ID。 – Son

+0

是的不同的ID。我不认为元素可以有相同的ID,它不会发出错误,但它也不起作用。 – anderish

-1

使用jQuery,您可以在addCss功能补充一点:

$('td').addClass('hide'); 
+0

请解释下投票,如问题的要求,这将隐藏TD标签。 –

+0

不是downvoter,但可能是因为(a)OP没有指定jQuery;和(b)包括jQuery这样一个琐碎的任务是不好的做法 – jasonscript

0

覆盖类document.getElementById("id").className = "newclass";
添加一个新的类document.getElementById("id").className += " anotherclass";

function addCss(){ 
 
document.getElementById("b").className = "hide"; 
 
} 
 

 
function newCss(){ 
 
document.getElementById("b").className = "show"; 
 
}
body { 
 
    font-size: 3em; 
 
    background: honeydew; 
 
} 
 

 
.hide { 
 
    display: none; 
 
} 
 

 
.show { 
 
    display: table-cell; 
 
}
<table> 
 
<tr> 
 
<td id=a style="background:skyblue">A</td> 
 
<td id=b style="background:yellowgreen">B</td> 
 
<td id=c style="background:gold">C</td> 
 
<td id=d style="background:orangered">D</td> 
 
</tr> 
 
</table> 
 

 
<button onclick="addCss()">hide B cell</button> 
 
<button onclick="newCss()">show B cell</button>