【问题标题】:Need to hide two CSS IDs with one (script)需要用一个(脚本)隐藏两个 CSS ID
【发布时间】:2022-08-20 21:39:30
【问题描述】:

我的页面上有一个带有以下代码的按钮:

<h5 onclick=\"flightFunction()\">One Way</h5>

<script type=\"text/javascript\">
function flightFunction() {
  document.getElementById(\"returnDate\").style.display = \"none\";
}

</script>

我试图做的只是添加第二个 document.getElementByID(\"rtField\").style.display = \"none\"; (带有闭合括号)到代码中,但是当我单击文本时,什么也没有发生。如果我只是添加上面的代码,则成功隐藏了两个元素之一。但是,我需要在单击文本时同时隐藏两个元素(一个使用 returnDate CSS ID,另一个使用 rtField CSS ID)。我应该为此功能使用不同的代码吗?

    标签: javascript html css


    【解决方案1】:

    这应该有效

    <h5 onclick="flightFunction()">One Way</h5>
    
    <script type="text/javascript">
    function flightFunction() {
      document.getElementById("returnDate").style.display = "none";
    document.getElementById("rtField").style.display = "none";
    }
    
    </script>
    

    但始终检查控制台是否有错误

    可能某些 ID 无效,从而终止函数

    【讨论】:

      【解决方案2】:

      只要给他们两个同一个班级

      <div id="returnDate" class="something">One Thing</div>
      <div id="otherReturnDate" class="something">Two Things</div>

      【讨论】:

        【解决方案3】:

        使用 this 关键字:

        function flightFunction() {
            this.style.display = "none";
        }
        

        HTML:

        <div id="rtField" onclick="flightFunction()">Hello</div>
        <div id="returnDate" onclick="flightFunction()">Hello</div>
        

        this 关键字将调用该函数的对象

        【讨论】:

        • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
        猜你喜欢
        • 1970-01-01
        • 2012-06-08
        • 2023-03-22
        • 1970-01-01
        • 2019-12-05
        • 2022-12-10
        • 1970-01-01
        • 2017-07-14
        • 1970-01-01
        相关资源
        最近更新 更多