Javascript:如何在 <p hidden> 中添加和删除隐藏
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49836397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript: how do you add and remove hidden in <p hidden>
提问by CptHowdyRD0
How do you add and remove 'hidden' from <p hidden>My Text<\p>? I tried removing the attribute and setting it to false but neither of them worked.
你如何添加和删除“隐藏” <p hidden>My Text<\p>?我尝试删除该属性并将其设置为 false 但它们都不起作用。
let p = document.getElementsByTagName('p');
let myText;
for (i = 0; i < p.length; i++) {
if (p[i].innerHTML == "My Text") {
myText = p[i];
break;
}
}
myText.removeAttribute("hidden"); // no effect
myText.setAttribute("hidden", false); // no effect
采纳答案by Wesley Gon?alves
It looks fine here. Try with this code if you wish.
这里看起来不错。如果您愿意,请尝试使用此代码。
index.html
索引.html
<html>
<head>
</head>
<body>
<p hidden>My Text</p>
</body>
</html>
script
脚本
let p = document.getElementsByTagName('p');
let myText;
for (i = 0; i < p.length; i++) {
if (p[i].innerHTML == "My Text") {
// console.log(myText, p[0].innerHTML);
myText = p[i];
break;
}
}
myText.removeAttribute("hidden");
You can see in codePen https://codepen.io/anon/pen/qozVaq
您可以在 codePen https://codepen.io/anon/pen/qozVaq 中看到
回答by John Luscombe
Could you set an ID on the p tag and interact with it that way?
你能在 p 标签上设置一个 ID 并以这种方式与之交互吗?
<p id="whatever" hidden>My Text</p>
And:
和:
let p = document.getElementById('whatever');
p.removeAttribute("hidden");
回答by ritesh.p
Removing comparison text works fine for me:
删除比较文本对我来说很好:
let p = document.getElementsByTagName('p');
let myText;
for (i = 0; i < p.length; i++) {
var txt = document.getElementsByTagName('p')[i].innerHTML;
if (p[i].innerHTML == txt) {
myText = p[i];
break;
}
}
myText.removeAttribute("hidden");
Here is the working version: https://jsfiddle.net/j0467m8m/15/
这是工作版本:https: //jsfiddle.net/j0467m8m/15/
回答by DCR
function show(){
x = document.getElementsByTagName('p');
if(x[0].style.visibility === "hidden"){
x[0].style.visibility = "visible"
}else{
x[0].style.visibility = "hidden"
}}
<p >this is hidden</p>
<button onClick='show()'>show</button>

