You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于《JavaScript & jQuery》中placeholder polyfill示例的错误疑问

关于placeholder兼容脚本的错误分析与验证

这是出自《JavaScript & jQuery - Interactive Front-End》一书的placeholder兼容脚本(polyfill)示例。你作为自学前端的新手,指出的脚本问题完全正确,具体分析如下:

问题核心

脚本开头的兼容性检测if ('placeholder' in document.createElement('input')) { return; }会直接在支持placeholder属性的浏览器中终止执行,只有不支持该属性的老旧浏览器才会进入后续polyfill逻辑。但在这些浏览器中,表单元素本身并没有placeholder这个DOM属性,访问el.placeholder会返回undefined,此时!el.placeholder结果为true,会触发continue跳过所有元素,导致整个polyfill完全失效。

正确的处理方式

应该读取元素的HTML属性值,用el.getAttribute('placeholder')来判断是否设置了placeholder——即使浏览器不支持该DOM属性,HTML标签上的placeholder属性依然可以通过getAttribute获取到。

以下是原示例代码:

(function() {                                        // Place code in an IIFE
  // Test: Create an input element, and see if the placeholder is supported
  if ('placeholder' in document.createElement('input')) {
    return;
  }

  var length = document.forms.length;               // Get number of forms
  for (var i = 0; i < length; i++ ) {               // Loop through each one - updated shorter syntax
    showPlaceholder(document.forms[i].elements);    // Call showPlaceholder()
  }

  function showPlaceholder(elements) {              // Declare function
    for (var i = 0, l = elements.length; i < l; i++) { // For each element
      var el = elements[i];                         // Store that element

      if (!el.placeholder) {                        // If no placeholder set
        continue;                                   // Go to next element
      }                                             // Otherwise

      el.style.color = "#666666";                      // Set text to gray
      el.value = el.placeholder;                    // Add placeholder text

      addEvent(el, 'focus', function () {           // If it gains focus
        if (this.value === this.placeholder) {      // If value=placeholder 
          this.value = '';                          // Empty text input
          this.style.color = "#000000";                // Make text black
        }
      });

      addEvent(el, 'blur', function () {            // On blur event
        if (this.value === '') {                    // If the input is empty
          this.value = this.placeholder;            // Make value placeholder
          this.style.color = "#666666";                      // Set text to gray
        }
      }); 
    }                                                // End of for loop
  }                                                  // End showPlaceholder()
}());

内容的提问来源于stack exchange,提问作者Animesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 01:07:33