Polyfill HTML5表单属性(用于输入字段)

前端之家收集整理的这篇文章主要介绍了Polyfill HTML5表单属性(用于输入字段)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是我使用的标记
<input type="text" form="myform" name="inp1" />
<form id="myform" name="myform">
    ...        
</form>

现在我意识到它不适用于旧IE,因此我正在搜索HTML 5 polyfill.

任何人都知道某个覆盖HTML5功能的polyfill?

解决方法

我写这个polyfill来模拟这样的功能,通过在表单提交时复制字段,在IE6中测试,它工作正常.
(function($) {
  /**
   * polyfill for html5 form attr
   */

  // detect if browser supports this
  var sampleElement = $('[form]').get(0);
  var isIE11 = !(window.ActiveXObject) && "ActiveXObject" in window;
  if (sampleElement && window.HTMLFormElement && (sampleElement.form instanceof HTMLFormElement || sampleElement instanceof window.HTMLFormElement) && !isIE11) {
    // browser supports it,no need to fix
    return;
  }

  /**
   * Append a field to a form
   *
   */
  $.fn.appendField = function(data) {
    // for form only
    if (!this.is('form')) return;

    // wrap data
    if (!$.isArray(data) && data.name && data.value) {
      data = [data];
    }

    var $form = this;

    // attach new params
    $.each(data,function(i,item) {
      $('<input/>')
        .attr('type','hidden')
        .attr('name',item.name)
        .val(item.value).appendTo($form);
    });

    return $form;
  };

  /**
   * Find all input fields with form attribute point to jQuery object
   * 
   */
  $('form[id]').submit(function(e) {
    // serialize data
    var data = $('[form='+ this.id + ']').serializeArray();
    // append data to form
    $(this).appendField(data);
  }).each(function() {
    var form = this,$fields = $('[form=' + this.id + ']');

    $fields.filter('button,input').filter('[type=reset],[type=submit]').click(function() {
      var type = this.type.toLowerCase();
      if (type === 'reset') {
        // reset form
        form.reset();
        // for elements outside form
        $fields.each(function() {
          this.value = this.defaultValue;
          this.checked = this.defaultChecked;
        }).filter('select').each(function() {
          $(this).find('option').each(function() {
            this.selected = this.defaultSelected;
          });
        });
      } else if (type.match(/^submit|image$/i)) {
        $(form).appendField({name: this.name,value: this.value}).submit();
      }
    });
  });


})(jQuery);

猜你在找的HTML5相关文章