我有一个函数(如下),当 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
我该怎么做?
最佳答案
当 <select>
时,为什么不直接设置之前的值?获得焦点(即在改变之前)?这样,您就可以使用委托(delegate)事件处理程序。例如...
$(document).on('focus', 'select', function() {
var $sel = $(this);
if (!$sel.data('prev')) {
$sel.data('prev', $sel.val());
}
});
关于javascript - 如何使用 JQuery 概括此函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28666238/