我找到了一个解决方案,使用这个答案:
// Get selector from any dom element
// @see https://stackoverflow.com/a/2068381/731138
var getPath = function(elem) {
var path;
var node = $(elem);
while (node.length) {
var realNode = node[0];
var name = realNode.localName;
if (!name) {
break;
}
name = name.toLowerCase();
if (realNode.id) {
return name + '#' + realNode.id + (path ? '>' + path : '');
} else if (realNode.className) {
name += '.' + realNode.className.split(/\s+/).join('.');
}
var parent = node.parent();
var siblings = parent.children(name);
if (siblings.length > 1) {
name += ':eq(' + siblings.index(node) + ')';
}
path = name + (path ? '>' + path : '');
node = parent;
}
return path;
}
// Return value of any element without knowledge of its type
var getValue = function(elem, contextSelector) {
if ($(elem).is('input[type="checkbox"]')) {
return ($(elem).prop('checked') == true);
}
if (($(elem).is('input[type="radio"]')) && ($(elem).attr('name') !== undefined)) {
return $(contextSelector + '>input[name="' + $(elem).attr('name') + '"]:checked').val();
}
if ($(elem).prop('value') !== undefined) {
return $(elem).val();
} else {
return $(elem).html();
}
}
然后,当我需要从任何选择器中恢复要发布的字段时,如下所示:
// Get all data to post
var elemSelector = getPath(elem);
var inputSelector = $(elem).data('input');
var inputData = {};
if (inputSelector !== undefined) {
if (inputSelector !== '') {
inputSelector = inputSelector + ' :input';
$.each($(inputSelector), function (index, node) {
if (($(node).attr('name') === undefined) && ($(node).attr('id') === undefined)) {
return true;
}
var key = $(node).attr('name');
if (key === undefined) {
key = $(node).attr('id');
}
inputData[key] = getValue(node, elemSelector);
});
} else {
inputData['value'] = getValue(elem, elemSelector);
}
}