【问题标题】:How to set an img tag with an id to false if the source is empty?如果源为空,如何将带有 id 的 img 标签设置为 false?
【发布时间】:2017-02-23 23:16:30
【问题描述】:

如果内部 html 没有分配图像源,我正在尝试将 ID 为 #myComputer 的 img 标签的可见性设置为 false。

HTML

    <img id="myComputer" src="assets/myComputer.png">

JS

    var myComputer = document.getElementById('myComputer').src;
    var myComputerVisible = true;

    if(myComputer == ""){
    myComputerVisible = false;
    };

当我删除源并检查控制台“myComputerVisible”时,即使我删除了 html 中的源,控制台“myComputerVisible”仍然显示为“true”:

    <img id="myComputer" src="">

仅纯 Javascript。请指教!谢谢!

【问题讨论】:

    标签: javascript html if-statement show-hide


    【解决方案1】:

    改用getAttribute

    var myComputer = document.getElementById('myComputer').getAttribute("src");
    var myComputerVisible = true;
    console.log("src is: " + myComputer);
    if (myComputer == "") {
      myComputerVisible = false;
    };
    
    console.log(myComputerVisible);
    &lt;img id="myComputer" src=""&gt;

    【讨论】:

      【解决方案2】:

      请使用getAttribute获取HTML标签任意属性的值。

       var myComputer = document.getElementById("myComputer").getAttribute("src");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-21
        • 2012-07-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多