将文本存储为变量,然后根据变量值更改css样式

时间:2018-05-09 18:51:43

标签: javascript html css function

我有一些简单的HTML:

<div>Below is the div id containing the attorney value. </div>
<div id="attorney"> 0 </div>
<div id="profiletab1">THIS IS THE DIV I WANT TO HIDE</div>

在页面加载时,当div.attorney的值=&#39; 0&#39;我想更改div.profiletab1 css display style="none"

我不确定我错过了什么。

<script type="text/javascript">
 function myfunc(){
   var atty= document.getElementById("attorney").value;
   if (atty=== '0'){
     document.getElementById("profiletab1").style.display = "none";
   }
 }
 window.onload = myfunc;
 </script>

3 个答案:

答案 0 :(得分:2)

你需要获取textContent,而不是值并修剪它,因为那里有空格:

function myfunc() {
    var atty = document.getElementById("attorney").textContent.trim();
    if (atty === '0') {
        document.getElementById("profiletab1").style.display = "none";
    }
}

答案 1 :(得分:0)

XMLHttpRequest属性通常仅保留在protected bool IsAjaxRequest() { return Request.Headers["X-Requested-With"] == "XMLHttpRequest"; } 元素上。 value怎么样?

input

此文字两边都有空格innerText,因此它不等于var atty= document.getElementById("attorney").value; // .innerText; 。要修剪间距,您可以使用0 0来返回String.prototype.trim()

atty.trim()

你的“这是我想要隐藏的DIV”是一个ID为“profiletab1”的人吗?这应该可行。

把它放在一起:

0

答案 2 :(得分:0)

您需要使用innerText而不是value。值是用于获取值=&#34; &#34;属性。

<div>Below is the div id containing the attorney value. </div>
<div id="attorney">0</div>
<div id="profiletab1">THIS IS THE DIV I WANT TO HIDE</div>

<script type="text/javascript">
function myfunc(){
    var atty = document.getElementById("attorney").innerText;
    if (atty=== '0')
    {
        document.getElementById("profiletab1").style.display = "none";
    }
}

window.onload = myfunc;
</script>