代码之家  ›  专栏  ›  技术社区  ›  Ben

如何使用JQuery概括此函数

  •  0
  • Ben  · 技术社区  · 9 年前

    我有一个函数(如下),当DOM加载时,它会查找每个select输入并添加一个属性 data-prev 跟踪 以前的 在值更改的情况下,所选值为。

    $( document ).ready(function() {
    
      //For each select field, add a data-prev attribute set for tracking the previous value for when it gets changed
      $('select').each(function(){
        $(this).attr("data-prev", $(this).val())
      });
    }
    

    现在,我的页面包括动态创建的选择字段(在页面加载后),我还需要设置 数据prev 属性所以,我在想,把上面的函数概括成类似

    function SetDataPrevAttr(element=None)
        if element is None:
            for each select field in DOM set the attribute data-prev to its current value
        else:
            for each select field in the descendant elements of element (including element) set the attribute data-prev to its current value
    

    我该怎么做?

    2 回复  |  直到 9 年前
        1
  •  1
  •   Phil    9 年前

    <select> 获得关注(即在变化之前)?这样,您可以只使用委托事件处理程序。例如

    $(document).on('focus', 'select', function() {
        var $sel = $(this);
        if (!$sel.data('prev')) {
            $sel.data('prev', $sel.val());                  
        }
    });
    

    JSFiddle Demo

        2
  •  0
  •   Chris Pietschmann    9 年前
    function SetDataPrevAttr(elem) {
        elem.each(function () {
            $(this).attr('data-prev', $(this).val());
        });
    }
    
    $(function() {
        SetDataPrevAttr($('select'));
    });
    

    然后,在添加每个新元素时,可以执行以下操作:

    var element = $('<select></select>').appendTo(document);
    SetDataPrevAttr(element);