【问题标题】:Typeof operator Trouble运营商类型问题
【发布时间】:2015-03-01 22:04:06
【问题描述】:

我有一个隐藏文本的 div。只有当另一个 div 的文本内容等于字符串时,才能显示此文本。为此,我编写了以下函数:

function show() {
    if(typeof genDiv.innerHTML == "string") {
        showDiv.innerHTML = fullhiragana[h];
    } else {
        alert("Please generate the Romaji before requesting the Hiragana to be displayed.");
    }
}
     //fullhiragana is an array that has the data that 'showDiv' is supposed to display.
      'h' is a var that randomly picks a string from fullhiragana.//

在某种程度上,它有效。如果我按下按钮,它会显示文本,但它会这样做 不管 其他 div 中的内容类型。如果第一个 div 中没有 no 内容,它甚至可以工作。也许我构造了 if 条件错误?请帮忙! 有关问题的进一步参考,请参阅此打印屏幕; http://prntscr.com/5o7q59

【问题讨论】:

  • genDiv.innerHTML是代表genDiv内容的HTML字符串。它总是一个字符串,即使它是空的。您是否要检查元素是否为空或其他?
  • @U2744SNOWFLAKE 哇,我不知道。即便如此,我正在检查 genDiv 的内容是否为字符串。即使在什么都没有的情况下,数据类型仍然不是字符串(我忘记了它是 undefined 还是 null 或者其他什么)
  • 不,如果什么都没有,它将是空字符串 ("")——即使对于像 <img> 这样的空元素也是如此。 (一般来说,“空”的东西不是这样,但它适用于 innerHTML 属性。)
  • 一个字符串。空字符串的类型仍然是"string"
  • @AlienC — innerHTML 是主机对象的属性,由W3C HTML 5 specification 定义。它使用以Let s be a string, and initialise it to the empty string. 开头的HTML fragment serialization algorithm。如果没有要序列化的内容,则返回空字符串。

标签: javascript html function conditional-statements typeof


【解决方案1】:

typeof(genDiv.innerHTML == "string") 总是为真。所以这是真的即使 div 是空的或者有一个数字或算术运算符,如 (+, &, %, -) 等...

如果第一个 div 没有内容,则 genDiv.innerHTML 为空字符串(“”)。

检查输入字段是否已输入内容的方法是:

if(genDiv.innerHTML.length>0) {
    showDiv.innerHTML = fullhiragana[h];
}

另外,如果要获取输入字段的内容,最好使用 genDiv.value 而不是 genDiv.innerHTML。

【讨论】:

    【解决方案2】:

    关于innerHTML.length 的用户,这应该可以在现代浏览器中使用,但请注意,即使没有文本,某些较旧的(IE)浏览器也可能返回true,因为innerHTML 属性可能包含空格。在检查该条件之前,您可能需要清除前导空格和尾随空格。

    【讨论】:

      【解决方案3】:

      根据 raneshu 的回答,一个空的 String 对象解析为 JavaScript 中的 falsy 值,即可以通过类型转换为 BooleanString 进行操作:

      if (!container.innerHTML) {
          console.log('#container has no content!');
      }
      

      有关工作示例,请参阅 this JSFiddle

      另外,here 的一些关于 JavaScript 中虚假值的信息,包括 Strings

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-03-22
        • 2020-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多