当元素的内容包含使用javascript的特定字符串时,我正在尝试隐藏一个元素。
这是我到目前为止所拥有的:
var y = document.getElementById("radio_ship0").innerHTML;
var x = y.includes("LTL Freight");
if (x == true) {
document.getElementById("divCheckoutQuestions").setAttribute("display",
"none");
}
<p id="radio_ship0">LTL Freight</p>
<div id="divCheckoutQuestions">test</div>
答案 0 :(得分:1)
var y = document.getElementById("radio_ship0").innerHTML;
var x = y.includes("LTL Freight");
if (x === true) {
document.getElementById("divCheckoutQuestions").style.display = "none"
}
尝试上面的一个。
答案 1 :(得分:1)
您应该使用.textContent而不是.innerHTML。同样,您可以避免声明“ x”,并将.setAttribute更改为.style。这样行之有效。
var y = document.getElementById("radio_ship0").textContent;
if ( y.includes("LTL Freight")) {
document.getElementById("divCheckoutQuestions")
.style.display = 'none'
}
<p id="radio_ship0">LTL Freight</p>
<div id="divCheckoutQuestions">test</div>
答案 2 :(得分:1)
您的条件还可以,但是您没有隐藏该元素。试试这个:
var y = document.getElementById("radio_ship0").innerHTML;
var x = y.includes("LTL Freight");
if (x == true) {
// check the .style.display = "none";
document.getElementById("divCheckoutQuestions").style.display = "none"
}
哦,顺便说一句,您的代码可以简化为:
var y = document.getElementById("radio_ship0").innerHTML;
if (y.includes("LTL Freight")) {
document.getElementById("divCheckoutQuestions").style.display = "none"
}
答案 3 :(得分:1)
display
不是一个属性,而是一个style属性,因此您不能像这样设置display属性。
var y = document.getElementById("radio_ship0").innerHTML.trim();
var x = y.includes("LTL Freight");
if (x) {
document.getElementById("divCheckoutQuestions").style.display = "none";
}
<p id="radio_ship0">LTL Freight</p>
<div id="divCheckoutQuestions">test</div>
答案 4 :(得分:1)
尝试一下:
x.style.display = y.includes("LTL Freight") ? "none" : "block" ;
var y = document.getElementById("radio_ship0").innerHTML ;
var x = document.getElementById("divCheckoutQuestions") ;
x.style.display = y.includes("LTL Freight") ? "none" : "block" ;
<p id="radio_ship0">LTL Freight</p>
<div id="divCheckoutQuestions">test</div>