我有一个函数(如下所示),当DOM加载时,它会找到每个选择输入,并添加一个属性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())
});
}
现在,我的页面包含动态创建的选择字段(在页面加载后),我还需要设置data-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
我该怎么做?
答案 0 :(得分:1)
为什么不在<select>
获得焦点时(即在变化之前)设置前一个值?这样,您就可以使用委托事件处理程序。例如......
$(document).on('focus', 'select', function() {
var $sel = $(this);
if (!$sel.data('prev')) {
$sel.data('prev', $sel.val());
}
});
答案 1 :(得分:0)
function SetDataPrevAttr(elem) {
elem.each(function () {
$(this).attr('data-prev', $(this).val());
});
}
$(function() {
SetDataPrevAttr($('select'));
});
然后在添加每个新元素时,您可以执行以下操作:
var element = $('<select></select>').appendTo(document);
SetDataPrevAttr(element);